数値のテキスト ファイルを開いて最後まで読み取る関数を定義しようとしています。関数が各行を読み取るとき、行を文字列として読み取り、条件を介して、FIRST インデックス スポット (つまり、値 0) のさまざまな可能な桁の各カウンターに +1 を追加する必要があります。
テキスト ファイルの例を次に示します。
1245
64356
345
12
863
私のプログラムは次のようなものを出力するはずです:
1: 2
2: 0
3: 1
4: 0
5: 0
6: 1
7: 0
8: 1
9: 0
>>
テキストファイルの行を文字列変数にしてから、その文字列を文字/文字列値と比較することに固執していると思います。を使用してwhileループを試しましたが、動作させることを期待(!filename.good)
してループに切り替えました。for
これが私のコードです。助けや建設的な批判は大歓迎です。
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
}