I am trying to define a function that will open a text file of numbers and read it all the way through. As the function reads each line, it should read the line as a string and then through conditionals add +1 to each counter for the different possible digits in the FIRST index spot (i.e. value 0).
Here is an example text file:
1245
64356
345
12
863
My program should output something like this:
1: 2
2: 0
3: 1
4: 0
5: 0
6: 1
7: 0
8: 1
9: 0
I think I am stuck at having the text file line be >>
to a string variable and then having that string be compared to a character/string value. I tried a while loop using (!filename.good)
, but switched to a for
loop in hopes of getting it to work.
Here is my code as follows - any help or constructive criticism would be greatly appreciated.
void analyzeData(std::string filename)
{
// declare the local filestreams i will be using in the function.
std::ifstream any_file_from_Main;
// assign actual file data to local filestreams
any_file_from_Main.open(filename.c_str());
//conditional to check if files opened, output error if they dont
if (!any_file_from_Main.good())
{
std::cout << "File did not open correctly." << std::endl;
exit(-1);
}
double sum;
std::size_t first_digit = 0;
//declare all counter variables
double one;
double two;
double three;
double four;
double five;
double six;
double seven;
double eight;
double nine;
//input the first line into string first_digit
any_file_from_Main >> first_digit;
//continue this loop while the file is not at the end
for (int i = 0; !any_file_from_Main.eof(); sum++)
{
if (first_digit[i] == "1") {
one++;
} else if (first_digit[i] == "2") {
two++;
} else if (first_digit[i] == "3") {
three++;
} else if (first_digit[i] == "4") {
four++;
} else if (first_digit[i] == "5") {
two++;
} else if (first_digit[i] == "6") {
six++;
} else if (first_digit[i] == "7") {
seven++;
} else if (first_digit[i] == "8") {
eight++;
} else if (first_digit[i] == "9") {
nine++;
}
// advances text file to next line and assigns value
// to string first_digit
any_file_from_Main >> first_digit;
}
// cout value of counter ints and percentages
}