我正在研究一個程序,它可以計算文件中的數字量,並將它們加在一起。你如何計算文件中的整數數量? (C++)
Ex。假設有一個包含數字「1 5 6 2 56 8」的.txt文件。你可以看到有6個數字,總和是78.我是這樣計算自己的。最後,我想要程序導出另一個文件,告訴我「數量的數量,並且數字的總和是:」
我該如何修改我的程序以對任何文件執行此操作?
這裏是我的源代碼:
ifstream inFile;
int value1, value2, value3, value4, value5, value6, value7, value8, value9, value10,
value11, value12, value13, value14, value15, value16, value17, value18, value19,
value20;
double average, sum;
//OPEN FILE
inFile.open("data.txt");
//ASSIGN VALUES WITH VARIABLES
inputFile >> value1;
inputFile >> value2;
inputFile >> value3;
inputFile >> value4;
inputFile >> value5;
inputFile >> value6;
inputFile >> value7;
inputFile >> value8;
inputFile >> value9;
inputFile >> value10;
inputFile >> value11;
inputFile >> value12;
inputFile >> value13;
inputFile >> value14;
inputFile >> value15;
inputFile >> value16;
inputFile >> value17;
inputFile >> value18;
inputFile >> value19;
inputFile >> value20;
// CLOSE FILE
input.close();
//CALCULATE THE SUM
sum = value1 + value2 + value3 + value4 + value5 + value6 + value7 + value8 + value9 + value10 +
value11 + value12 + value13 + value14 + value15 + value16 + value17 + value18 + value19 + value20;
//CALCULATE THE AVERGAGE
average = sum/20;
ofstream outputFile;
outputFile.open("results.txt");
outputFile << "The number of the values is: 20" << endl;
outputFile << "The total is: " << sum << endl;
outputFile << "The average is: " << average << endl;
outputFile.close();
return 0;
}
你應該學會循環和數組,也看看這個http://stackoverflow.com/questions/236129/split-a-string -in-c –
另請參閱'std :: vector',因此您不需要多少變量。 –