我被賦予了作業分配以生成一個包含隨機數行的txt文件,每個行都有一個隨機數量的整數,範圍介於最小值和最大值。很多蘭特()的樂趣。在C++中使用getline()時,沒有從文本文件中獲取所有行
無論如何,這是簡單的部分。問題的第二部分是讀取第一個文件並創建包含一些統計信息的第二個文件,例如:文件中所有整數的總和,它們的平均值,最小值和最大值以及我的主要問題:總和在每一行中的所有整數。
我已經寫以下代碼:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
string newLine;
stringstream ss;
int newInput = 0, oldInput = 0;
int lineSum = 0;
int lineCounter = 0;
int allSum = 0;
int intCounter = 0;
double averageOfAll = 0;
int minInt = 0;
int maxInt = 0;
.... //生成所述第一文件。這裏沒有問題。
ifstream readFile;
readFile.open("inputFile.txt");
ofstream statFile;
statFile.open("stat.txt");
if(readFile.is_open()) {
while (getline(readFile, newLine)) { //my problem should be somewhere
//around here...
ss.str("");
ss << newLine;
while(!ss.eof()) {
oldInput = newInput;
ss >> newInput;
cout << newInput << endl;
lineSum += newInput;
allSum += newInput;
intCounter++;
minInt = min(oldInput, newInput);
maxInt = max(oldInput, newInput);
}
lineCounter++;
statFile << "The sum of all integers in line " << lineCounter
<< " is: " << lineSum << endl;
lineSum = 0;
}
readFile.close();
averageOfAll = static_cast<double>(allSum)/intCounter;
statFile << endl << endl << "The sum of all integers in the whole file: "
<< allSum;
statFile << endl << "The average of value of the whole stream of numbers: "
<< averageOfAll;
statFile << endl << "The minimum integer in the input file: "
<< minInt;
statFile << endl << "The maximum integer in the input file: "
<< maxInt;
statFile << endl << endl << "End of file\n";
} else
cout << endl << "ERROR: Unable to open file.\n";
statFile.close();
return 0;
}
運行程序時,好像我做循環遍歷文件中的所有行。然而,他們只收集來自第一線的整數,而其餘部分保持爲0。
我會後我的輸出的屏幕截圖,但我沒有足夠的代表:( 誰能幫幫忙?
它的工作!
inputFile.txt^
statFile.txt(我的輸出)^
就像P0W和James Kanze建議的那樣,這是一個標誌問題和濫用我的串流。我更正了我的代碼,如下所示:
.
.
.
while (getline(readFile, newLine)) {
stringstream ss(newLine);
while(ss >> newInput) {
lineSum += newInput;
allSum += newInput;
intCounter++;
minInt = min(minInt, newInput);
maxInt = max(maxInt, newInput);
}
.
.
.
謝謝大家!
您可以將C++添加到主題列表。很多人可能不會遵循更精確的標籤(或者甚至知道它們存在)。 – 2014-10-03 16:11:06
剛剛做過,JGrice建議編輯我接受:) 謝謝大家 – 2014-10-03 16:13:45