从行读取时,ifstream文件被清除

时间:2018-10-25 15:56:27

标签: c++ ifstream

我正在尝试从C ++中的输入纺织品读取由空格分隔的字符。我已经成功打开了文件并能够遍历它。但是,每当我尝试从文件中的字符分配变量时,这些行似乎都被清除了。第一行的变量设置正确,但不在第一行之后。我不确定是否错误地访问了infile,是否缺少标志或是否有更好的方法来访问字符。

代码:

int lineNumber = 0,*linesMaxVal = new int[lineCount];
string line;
while (getline(infile, line)) {

    cout << "line # is " << lineNumber << " line val is: " << "'" << line << "'" << endl;

    int x1,x2,x3,x4,x5,max;
    infile >> x1 >> x2 >> x3 >> x4 >> x5;
}

如果删除了“ infile >> x1 >> x2 >> x3 ...等”行,则输出如下(正确)

line # is 0 line val is: '0 0 0 0 0'
line # is 0 line val is: '1 2 3 4 5'
line # is 0 line val is: '5 4 3 2 1'
line # is 0 line val is: '5 100 1000 10000 10500'
line # is 0 line val is: '99999 99999 99998 99999 99999'
line # is 0 line val is: '-1 0 0 0 -1'
line # is 0 line val is: '-9999 -9999 -9998 -9999 -9999'
line # is 0 line val is: '50 1234 457 789 7'
line # is 0 line val is: '123240 -124 -453 234 -99999'
line # is 0 line val is: '234 235 -109 0 12'
line # is 0 line val is: '777 987 234 345 111'
line # is 0 line val is: '12 0 -19 27 19'
line # is 0 line val is: '0 0 0 0 0'
line # is 0 line val is: '-99 -900 45 20 10'
line # is 0 line val is: '13 -56 99 123 90'
line # is 0 line val is: '0 0 1 -11 -1'
line # is 0 line val is: ''

否则,如果保留了infile行并定义了变量,则输出如下。

line # is 0 line val is: '0 0 0 0 0'
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''
line # is 0 line val is: ''

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

infile >> x1 >> x2 >> x3 >> x4 >> x5;

读取行上的所有数字,但将换行符留在流中。

然后返回循环的开头并运行:

getline(infile, line)

哪个立即会看到换行符,所以它会为您提供一个空字符串,吃掉换行符并继续前进。

这里最大的问题是提取运算符(>>)留在流中的空白处(在本例中为换行符),而getline则吃掉了终止处的所有分隔符。混合这两者可能会引起一点打ic。

一种可能的解决方法是在提取运算符之后添加一个ignore,以使换行符脱离流。


经过in chat的交谈之后,您似乎想遍历文件并在每一行中找到最大值。我建议使用向量存储每行的值,并使用算法库查找最大值:

//Our temp vector. It'll hold a line worth of ints
vector<int> line(5);

while(true) { //one loop = one line

    //Loop and read 5 ints (one line's worth) into the vector 
    for(int x = 0; x < 5 && infile >> line.at(x); x++) { }

    if(!infile) { break; } //if we read through everything, we're done!

    //find the biggest value in the vector
    int biggest = *max_element(line.begin(), line.end());

    //Do some things with it...
    cout << "Biggest is: " << biggest << endl;
}

有关有效的演示,请参见此处:ideone