I need some help with this.
I am running through some payroll data.
I have run a function that reads a .txt file, and then stores it in arrays. I am now trying to write a function that allows you to add to those arrays (they are arrays of 32 but only have 20 elements from the file) So it needs to loop through the arrays, make sure they do not go out of bounds, and then add the additional data types to the arrays. Here is how it looks for me. There are no errors, but when i run it, it does nothing:
string AddPayrollData(array<double, kMaxSize> &hours,
array<char, kMaxSize> &pay_type,
array<double, kMaxSize> &pay_rate,
array<string, kMaxSize> &names,
double hours_worked, char pay_t, double pay_r, string full_name,
int &size )
{
int i = 0;
while (size < kMaxSize && i < size)
{
if (hours[i] > 168)
{
cout << "Hours is out of range, set to 0" << endl;
hours[i] = 0;
}
if (pay_type[i] != 'h' || 's')
{
cout << "Incorrect pay type, set to s " << endl;
pay_type[i] = 's';
}
if (pay_rate[i] < 7.25)
{
cout << "Pay is less than minimum wage, set to 7.25 " << endl;
pay_rate[i] = 7.25;
}
if (names[i].find(","))
{}
else
{
cout << "Name Is not in last, first format" << endl;
names[size] = "unknown";
}
i++;
}
if(size >= kMaxSize)
{
cout << "Arrays are full, no payroll data added" << endl;
}
else
{
hours_worked = hours[size];
pay_t = pay_type[size];
pay_r = pay_rate[size];
full_name = names[size];
size++;
}
return "";
}
Thanks for the help!
There seem to be a few issues here. Some have been dealt with in the comments above. So I will mention the others.
The most important issue is that the purpose of the function is confused. It is both validating the existing data and adding (but not validating) new data. Nothing wrong with either of these things, but they should be separate functions. Or maybe this function should add and validate the new data but leave the existing data alone.
In the validating part, there are some mistakes already mentioned, plus names[size] = "unknown"; which should be names[i] = "unknown";.
In the adding part the problem is that the assignments are performed the wrong way round
hours_worked = hours[size];
pay_t = pay_type[size];
pay_r = pay_rate[size];
full_name = names[size];
should of course be
hours[size] = hours_worked;
pay_type[size] = pay_t;
pay_rate[size] = pay_r;
names[size] = full_name;
Finally for some strange reason the function returns a string. Just make it a void function.
Related
I've been struggling with a homework assignment that counts the amount of instances a uppercase letters, lowercase letters, and numbers in a string. appears in a string.
I'm using a one-dimensional array with a constant size of 132 to store the entered string, and I need to use two functions. One needs to count the amount of letter occurrences in the string and the other function will execute the output something similar to above. I'm struggling most with the letter counting aspect of the program itself.
Currently, this is what my current homework resembles for the most part. It's a work in progress (of course) so errors in the code are very likely.
void LetterCount(char c_input[], int l_count)
{
// code to count letters
}
void CountOut(//not sure what should go here yet until counting gets figured out)
{
// code that handles output
}
int main()
{
const int SIZE = 132;
char CharInput[SIZE];
int LetterCount = 0;
cout << "Enter a string of up to 132 characters in size: ";
cin.getline(CharInput, SIZE);
cout << "You entered: " << CharInput << endl;
Count(CharInput);
CountOut(//not sure what goes here yet);
return 0;
}
The output would look something like:
a - 2
b - 1
c - 1
d - 0
e - 1
etc...
I've tried some experimentation with for loops to count the letters and have seen some examples of the function gcount(), but I haven't gotten anything to work. Does anyone have a suggestion as to how I would count the letters in an inputted string?
map is a very efficient data structure here
#include <iostream>
#include <map>
using namespace std;
int main(){
string str = "a boy caught 2 fireflies";
map<char, int> str_map;
for(auto x : str) ++str_map[x];
for(auto x : str_map) cout << x.first << ' ' << x.second << '\n';
}
What you want is to build a simple histogram, and it's pretty easy to do. Since what you're looking at is chars, and there can be 256 possible values of an 8-bit char (in practice your input string probably uses less, but we'll be conservative here because memory is cheap), you'll want to start with an array of 256 ints, all of them initialized to zero. Then iterate over the chars your string, and for each char in your string, use that char-value as an offset into the array(*), and simply increment that item in the array.
When you're done, all that remains is to iterate over the ints in the array and print out the ones that are non-zero, and you're done.
(*) you may want to cast the char to unsigned char before using it as an offset into the array, just to avoid any chance of it being interpreted as a negative array-index, which would result in undefined behavior (this is only an issue if your input string contains ASCII characters 128 and higher, so it may not matter in your case, but it's always good form to make code that does the right thing in all cases if you can)
As Jeremy frisner said you're building a histogram, but I disagree with the types used.
You'll want to declare your histogram like so:
size_t histogram[sizeof(char)*CHAR_BIT] = {0};
The size_t because you might overflow without it, and you need enough space if it's a nonstandard byte size.
As for printing it out. You should take a look at an ASCII table and examine which values you need to print out.
You could do it by comparing c-strings with other c-strings. But with chars and strings you can get errors like: "const *char cant be compared with strings". So you'll have to compare each c string(array) index with other c string indexes. In this program I use if statements to look for certain vowels. The way it works is that each "string alphabet_letter" is equal to it's respective lowercase and capital letters (for comparison). this is a very redundant way to do it and, if you want to count all total letters, perhaps you should try a different way, but this method doesn't use very complicated methods that require deeper understanding.
using namespace std;
int main(){
int vowel;
string A = "aA";
string E = "eE";
string I = "iI";
string O = "oO";
string U = "uU";
string str;
string str1;
bool userLength = true;
int restart = 0;
do{
cout << "Enter a string." <<endl;
getline(cin, str);
int VowelA = 0;
int VowelE = 0;
int VowelI = 0;
int VowelO = 0;
int VowelU = 0;
for(int x = 0; x < 100; x++){
if(restart == 1){
restart = 0;
x = 0;
}
if(A[0] == str[x]){
VowelA = VowelA + 1;
}
if(E[0] == str[x]){
VowelE = VowelE + 1;
}
if(I[0] == str[x]){
VowelI = VowelI + 1;
}
if(O[0] == str[x]){
VowelO = VowelO + 1;
}
if(U[0] == str[x]){
VowelU = VowelU + 1;
}
if(A[1] == str[x]){
VowelA = VowelA + 1;
}
if(E[1] == str[x]){
VowelE = VowelE + 1;
}
if(I[1] == str[x]){
VowelI = VowelI + 1;
}
if(O[1] == str[x]){
VowelO = VowelO + 1;
}
if(U[1] == str[x]){
VowelU = VowelU + 1;
}
int strL = str.length();
if(x == strL){
cout << "The original string is: " << str << endl;
cout << "Vowel A: "<< VowelA << endl;
cout << "Vowel E: "<< VowelE << endl;
cout << "Vowel I: "<< VowelI << endl;
cout << "Vowel O: "<< VowelO << endl;
cout << "Vowel U: "<< VowelU << endl;
cout << " " << endl;
}
}
char choice;
cout << "Again? " << endl;
cin >> choice;
if(choice == 'n' || choice == 'N'){userLength = false;}
if(choice == 'y' || choice =='Y')
{
restart = 1; userLength = true;
cin.clear();
cin.ignore();
}
//cout << "What string?";
//cin.get(str, sizeof(str),'\n');
}while(userLength == true);
}
/*
Sources:
printf help
http://www.cplusplus.com/reference/cstdio/printf/
This helped me with the idea of what's a vowel and whats not.
http://www.cplusplus.com/forum/general/71805/
understanding gets()
https://www.programiz.com/cpp-programming/library-function/cstdio/gets
Very important functional part of my program...Logic behind my if statements, fixed my issues with string comparison
What i needed to do was compare each part of one cstring with another c string
strstr compares two strings to see if they are alike to one another this source includes that idea-> https://www.youtube.com/watch?v=hGrKX0edRFg
so I got the idea: What is one c string was all e's, I could then compare each index for similarities with a c string whos definition was all e's.
At this point, why not just go back to standard comparison with strings? But you cant compare const chars to regular chars, so I needed to compare const chars to const chars
hence the idea sparked about the c strings that contained both e and E.
https://stackoverflow.com/questions/18794793/c-comparing-the-index-of-a-string-to-another-string
https://stackoverflow.com/questions/18794793/c-comparing-the-index-of-a-string-to-another-string
Fixed Error with using incremented numbers outside of involved forloop.
https://stackoverflow.com/questions/24117264/error-name-lookup-of-i-changed-for-iso-for-scoping-fpermissive
understanding the use of getline(cin, str_name)
https://stackoverflow.com/questions/5882872/reading-a-full-line-of-input
http://www.cplusplus.com/reference/istream/istream/getline/
http://www.cplusplus.com/forum/beginner/45169/
cin.clear - cin.ignore --fixing issue with cin buffer not accepting new input.
https://stackoverflow.com/questions/46204672/getlinecin-string-not-giving-expected-output
*/
I'm a newbie C++ programmer. I've written a basic emotion checker that reacts based on your reply that gets fetched from an array. I'm wondering how to make it so that the replies work in both upper and lower case when typed in? E.g. when the user types in "happy" or "Happy" both would work. I've read about switch statements and toupper/tolower but I'm lost on how to implement these for my code. Here it is:
// Array of emotions
string positive[] = {"happy", "pleased", "joyful", "excited", "content", "cheerful", "satisfied", "positive"};
string negative[] = {"unhappy", "sad", "depressed", "gloomy", "down", "glum", "despair", "negative"};
string reply;
cout << "Please state your current emotions." << endl;
cin >> reply;
for (int i = 0; i < 10; i++)
if (reply == positive[i])
{
cout << "I am glad to hear that!" << endl;
}
else if (reply == negative[i])
{
cout << "I am sorry to hear that." << endl;
}
You would want to add a step in to process the string reply after reading it in.
One solution would be to iterate over the length of reply and call tolower on each character in the string.
An example modified from http://www.cplusplus.com/reference/cctype/tolower/
int i = 0;
while (reply[i]) {
c=reply[i];
reply[i] = tolower(c);
i++;
}
Then when you compare the strings you don't need to worry about case.
First of all, write a function named equals to compare two world is the same or not by convert all character of a string to lowercase. example:
bool equals(string status, string userInput)
{
//lowercaseStatus = convert userInput to lowercase
//lowercaseUserInput = convert status to lowercase
return lowercaseStutus == lowercaseUserInput;
}
Then use the function in for loop:
for (int i = 0; i < 10; i++)
if (equals(positive[i],reply))
{
cout << "I am glad to hear that!" << endl;
}
else if (equals(negative[i],reply))
{
cout << "I am sorry to hear that." << endl;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include<iostream>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
struct studentType
{
string studentFName[20];
string studentLName[20];
string studentData[20][3];
int testscore[20][5];
char grade[20];
};
studentType s;
int main()
{
int index;
int maxindex;
int maxindex1;
int coldex;
int coldex1;
int totalscore[20];
double avscore[20];
double highscore;
double highindivscore;
maxindex = 0;
maxindex1 = 0;
coldex1 = 0;
ifstream infile;
infile.open("test.txt");
for(index = 0; index < 20; index++)
{
infile >> s.studentFName[index] >> s.studentLName[index] >> s.testscore[index][0] >> s.testscore[index][1] >> s.testscore[index][2] >> s.testscore[index][3] >> s.testscore[index][4];
totalscore[index] = ((s.testscore[index][0]) + (s.testscore[index][1]) + (s.testscore[index][2]) + (s.testscore[index][3]) + (s.testscore[index][4]));
avscore[index] = (static_cast<double>(totalscore[index])/5);
if(avscore[index]<= 100)
{
s.grade[index] = 'A';
}
if(avscore[index]<= 89.9)
{
s.grade[index] = 'B';
}
if(avscore[index]<= 79.9)
{
s.grade[index] = 'C';
}
if(avscore[index] <= 69.9)
{
s.grade[index] = 'D';
}
if(avscore[index] <= 59.9)
{
s.grade[index] = 'F';
}
}
for (index = 0; index < 20; index++)
{
cout << s.studentLName[index] << "," << " " << s.studentFName[index] << " " << s.testscore[index][0] << " " << s.testscore[index][1] << " " << s.testscore[index][2] << " " << s.testscore[index][3] << " " << s.testscore[index][4] << " " << s.grade[index] << endl;
}
cout << endl;
for (index = 1; index < 20; index++)
for (coldex = 0; coldex < 5; coldex++)
{
if (s.testscore[maxindex1][coldex1] < s.testscore[index][coldex])
{
maxindex1 = index;
coldex1 = coldex;
}
}
highindivscore = s.testscore[maxindex1][coldex1];
for (index = 1; index < 20; index++)
{
if (avscore[maxindex] < avscore[index])
{
maxindex = index;
}
}
highscore = avscore[maxindex];
cout << s.studentFName[maxindex] << " " << s.studentLName[maxindex] << " Achieved The Highest Average Test Score Of A: " <<highscore <<endl;
cout << s.studentFName[maxindex1] << " " << s.studentLName[maxindex1] << " " << s.testscore[maxindex1][coldex1] << endl;
infile.close();
system("pause");
return 0;
}
here is the homework question, i know i did it wrong which is why i need help. How do i make main function calls. I am new to this. I have this lab that's got me stumped. The assignment reads (emphasis mine):
Write programs for the following and test to make sure they work. Please follow the book’s guidelines or my style guidelines to write code. Write a program that reads students’ names followed by their test scores from the given input file. The program should output to a file, output.txt, each student’s name followed by the test scores and the relevant grade.. Student data should be stored in a struct variable of type StudentType, which has four components: studentFName and studentLName of type string, testScore of type int and grade of type char. Suppose that the class has 20 students. Use an array of 20 components of type StudentType. Your program must contain at least the following functions:
A function to read the students’ data into an array.
A function to assign the relevant grade to each student.
Your program should output each student’s name in this form: last name followed by a comma, followed by a space, followed by the first name; the name must be left justified. Moreover, other than declaring the variables and opening the input and output files, the function main should only be a collection of function calls.
This is called refactoring. I guess for the assignment you want to move everything that is in main into individual functions. You could just cut and paste the whole body of main and move it to one function and call it in main. I don't really think that is the point of the assignment though.
Instead, read over main and separate/extract procedures. You should separate main into functions that do one thing i.e. handle input/output, loop, check some variable and return a letter, etc. These kind of changes not only make the program much easier to understand and come back to later, but also make it much easier to reuse procedures that are repeated throughout the program.
Your code looks fine logically and should work, however, what your homework is asking of you is to essentially code with good style and separate the sections of the program into functions.
Essentially, as an easy fix, just place different sections that do similar things from the code into void functions. For example, this cpp segment:
void function1();
void function2();
void function3();
void main(){
function1();
function2();
function3();
return 0;
}
void function1(){
// Your code. Ex: Some large algorithm.
}
void function2(){
//More code, for a different algorithm. Maybe some input or output.
}
void function3(){
//The final code you want the program to execute.
}
And then pass parameters and adjust return types as needed. It makes the code easier to follow, especially if you have the functions named after what they do such as gradingLogic() or studentOutput().
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am making a program that allows a user to make bank accounts and save them too a file, you can also delete them. I am having issues with my code for deleting an account on the file, my function for deleting the account looks like this.
int deleteCustomer(account acc[], int numCust)
{
string target;
bool accFound = false;
int count = 0;
cout << "Enter account number: ";
cin >> target;
for (int i = 0; i < numCust; i++)
{
if (acc[i].acctNum == target)
{
accFound = true;
break;
}
count++;
}
if (accFound == false)
{
cout << "That account does not exist." << endl;
system("pause");
system("cls");
}
else if (accFound == true)
{
ofstream outFile;
outFile.open("customer.dat");
for (int i = count; i < numCust - 1; i++)
{
outFile << acc[i+1].acctNum;
outFile << '#';
outFile << acc[i+1].name;
outFile << '#';
outFile << acc[i+1].cBal;
outFile << '#';
outFile << acc[i+1].sBal;
outFile << '#';
}
numCust--;
outFile.close();
}
return numCust;
}
The function is supposed to overwrite the account selected by the user by saving the file ahead of it to the previous spot and return the new number of customers. It appears to run through fine but it does not do anything and I am uncertain as to why. Any input would be helpful, thank you.
Several problems here:
Your account lookup should be working, but you're overcomplicating this a bit (you'd only need one value rather than three, but let's skip that for now). If you're interested let me know.
You're never actually removing any account (just reducing the number of total accounts; which will then cause the last entry to be removed).
When saving you accounts to the file, you start at that selected index, which doesn't make any sense at all.
Let's assume you've got 10 accounts, indices 0 through 9.
The user picks the account at index 5.
You save accounts index 6 through 9(!) only.
The user picks the account at index 0.
You save accounts index 1 through 9 only.
Some style things:
You essentially store the selected account's index in count. That's fine, but very misleading. Don't ever use misleading variable names. As you might be able to tell from my comment above, I misread that part as well.
Rather than writing if (booleanValue == true) you could just write if (booleanValue), which results in the same code, but is shorter and might be faster to read. In a similar way, you could replace if (booleanValue == false) with !booleanValue.
Don't omit namespaces like std, if you can (e.g. use std::string rather than string and avoid using namespace std;) to avoid writing ambigious code. If some other namespace you use has string (or any other member) as well, you'll either have to explicitly name the namespace anyway or you're at least confusing others reading your code. Also there's always the potential bug introduced by unintentionally using a different type.
Fixing the actual problem:
I assume this is some homework assignment or some tutorial/class code or anything similar? If so, don't just copy the following code and instead try to think about how it's working. Once you understood, implement it yourself and only use my snippets if you're really stuck.
In general, it's good software design to keep code and functions minimal. Don't create "super functions" that do several things. Also try to make code reusable, so in case you change something, you're able to adjust it in one place only.
Take your code above for example. Whenever you add, delete, or update an account, you'll have to write the new file. Did you plan on replicating the same code multiple times? If you'd have to adjust your file format, you'd have to change it everywhere.
You'll also need some way to actually remove customer datasets. As you might be aware, deleteing entries in an array would require you to move all entries behind it (to keep it continguous). This can be a very expensive operation.
To avoid this, I'm adding a new member bool valid to account. By default, this is set to false. Once there's some data put there (either through reading from a file or by the user), it's value is set to true.
So instead split this into two separate functions (moving the common code - saving - to its own function):
// By returning an integer value, you're able to communicate issues or problems
// without having to rely on exceptions (in case you're using C++).
// Note that I don't do any error checking here for simplicity.
// Parameters:
// filename - the target file to write
// acc - the array holding all customer accounts
// size - the maximum amount of values in acc
// Return value: 0, if everything went fine
// (I skipped actual error handling to keep it simple!)
int saveCustomers(const char *filename, account acc[], int size) {
std::ofstream outFile(filename);
// Iterate over all entries
for (int i = 0; i < num; ++i) {
// Do we actually have to store the account?
if (acc[i].valid) {
outfile << acc[i].acctNum << '#' << acc[i].name; // write all the values the way you did
}
}
outFile.close();
return 0; // Everything ok
}
Now that this is done, you're able to create your functions to modify your customer data:
int deleteCustomerByNumber(account acc[], int num, std::string target) {
// Iterate over all accounts and look for the selected one
for (int i = 0; i < num; ++i) {
// Only check valid accounts and see whether it's the target
if (acc[i].valid && acc[i].acctNum == target) {
acc[i].valid = false; // Mark it as invalid
return 0; // Everything ok
}
}
return 1; // Didn't find it!
}
In a similar way you can look for empty/unused entries to actually write data to them.
Bonus - alternative (STL) approach:
Since you're using C++, I'd suggest you use a different data structure, not just a simple array:
If you use a STL container (more specific: a map), you're able to handle everything a lot easier.
#include <map>
// Create a typedef to simplify expressions
typedef std::map<std::string, account> accmap;
// All accounts would be stored in this object:
accmap accounts;
// To do a quick lookup of any account:
accmap::const_iterator a = accounts.find(accountNumber);
if (a == accounts.end())
;// Account not found!
else {
a->first; // This is your account number
a->second; // This is your `account` object
}
// To delete a specific account:
accounts.erase(accountNumber)
// To create a new account simply access it:
accounts[accountNumber].name = newName;
You need to save all of the records before the index and after the index, otherwise you are effectively deleting more than just the one account. Presumably you should also remove the record from the input array as well. You are also not doing any error handling on the input or output. And you need to fix your output loop, it is not using indexes correctly.
Try this:
int deleteCustomer(account acc[], int numCust)
{
string target;
int accFound = -1;
cout << "Enter account number: ";
if (cin >> target)
{
for (int i = 0; i < numCust; ++i)
{
if (acc[i].acctNum == target)
{
accFound = i;
break;
}
}
}
if (accFound == -1)
{
cout << "That account does not exist." << endl;
system("pause");
system("cls");
}
else
{
for (int i = accFound+1; i < numCust; ++i)
acc[i-1] = acc[i];
--numCust;
ofstream outFile;
outFile.open("customer.dat");
for (int i = 0; (i < numCust) && (outFile); ++i)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
if (!outFile)
cout << "Error saving customer file" << endl;
}
return numCust;
}
If you don't want to update the array, then you can do this instead:
int deleteCustomer(account acc[], int numCust)
{
string target;
int accFound = -1;
cout << "Enter account number: ";
if (cin >> target)
{
for (int i = 0; i < numCust; ++i)
{
if (acc[i].acctNum == target)
{
accFound = i;
break;
}
}
}
if (accFound == -1)
{
cout << "That account does not exist." << endl;
system("pause");
system("cls");
}
else
{
ofstream outFile;
outFile.open("customer.dat");
for (int i = 0; (i < numCust) && (outFile); ++i)
{
if (i != accFound)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
}
if (!outFile)
Cout << "Error saving customer file" << endl;
--numCust;
}
return numCust;
}
Lastly, when updating a file, it is a good idea to write the new data to a temp file first, then replace the original file with the temp file only if everything is successful. That way you reduce the risk of corrupting the original file.
To "deleting an account on the file", this part of code:
for (int i = count; i < numCust - 1; i++)
{
outFile << acc[i+1].acctNum;
outFile << '#';
outFile << acc[i+1].name;
outFile << '#';
outFile << acc[i+1].cBal;
outFile << '#';
outFile << acc[i+1].sBal;
outFile << '#';
}
should be
for (int i = 0; i < numCust; i++)
{
if(i == count) continue;// remove the account user selected
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
Ok so my project is a program that analyses a .txt file that has a bunch of DNA strands of varying lengths. I got it all to work in 3 functions but my teacher wants us to us oo programming. So i put my code in a class and broke it up into different functions. Now, however my variables seem to randomly change their value and I don't know why.
I ran a bunch of tests with my "sum" variable (but it is not the only one doing this) and it calculates the correct value in the function but if I cout the value of "sum" back in my main, the value is changed to a ridiculous number.
Here is the code: it is not my whole program just where the problem variable is and how it is used.
If this isnt enough code to show the problem i can add more i just didnt want to make it cluttered.
DNAProcessing.cpp
void DNAProcessing::CalcSumAndMean()
{
int lineLength = 0;
int lineCounter = 0;
int wholeFileStringLen = 0;
double sum = 0;
double mean = 0;
string wholeFileString = "";
string line;
bool filefail = false;
ifstream DNAFile;
DNAFile.open(nameoffile.c_str());
if(DNAFile.fail())
{
filefail = true;
return;
}
else
{
cout << "\nYour data was processed\n" << endl;
}
while(DNAFile >> line)
{
//cout << line << endl;
lineCounter += 1;
lineLength = line.length();
sum += lineLength;
wholeFileString += line;
}
cout << "sum: " << sum << endl; // with my test .txt file this outputs 736
mean = (sum / lineCounter);
wholeFileStringLen = wholeFileString.length();
cout << "sum: " << sum << endl; // with my test .txt file this outputs 736
}
main.cpp
int main()
{
srand(time(0));
bool noexit = true;
string yesorno;
string filename;
while(noexit == true)
{
cout << "Would you like to process a list of DNA strings? (y/n)" << endl;
cin >> yesorno;
if((yesorno == "y") || (yesorno == "Y" ))
{
cout << "please input the name of the file you wish to process." << endl;
cin >> filename;
DNAProcessing DNAStrandFile(filename);
DNAStrandFile.CalcSumAndMean();
cout << "sum: " << DNAStrandFile.sum << endl; //for some reason sum turns into 3.18337e-314 and i have no clue why
if (DNAStrandFile.filefail == false)
{
cout << "sum: " << DNAStrandFile.sum << endl; // same here
DNAStrandFile.CalcNucleobaseRelProb();
DNAStrandFile.CalcBigramRelProb();
DNAStrandFile.CalcVarianceAndStndDev();
DNAStrandFile.CalcNormRand();
DNAStrandFile.PrintData();
DNAStrandFile.PrintNewList();
}
else
{
cerr << "No file found" << endl;
}
}
else if((yesorno == "n") || (yesorno == "N"))
{
noexit = false;
}
else{}
}
}
output while passing my test .txt file into this program.
sum: 736
sum: 736
sum: 3.18337e-314
sum: 3.18337e-314
Since sum is declared as double, it's value of 0 may not be stored exactly as zero, for all practical purposes, value of 3.18337e-314 can be considered as zero. You may define a threshold value
double epsilon = 0.00001 ; // depending on precision
and if sum < epsilon, sum = 0.0 (not needed though)
In your example, you have used sum as a local variable as well, either don't declare local variable, just use the member variable or declare the local variable as different name to avoid confusions
The value of a local variable is valid within the scope of the function,thats why you are getting correct answer inside method.
But no value is returned back,therefore garbage value is printed in the main.
Try sending the variable in the method by reference, then their exact value will be available in main also. Try it.