对Getline的工作方式有更深入的深度



因此,例如,如果我有一个.dat文件

410000 1905 7 50
410001 2015 3 25 
410023 1857 12 -25

我试图弄清楚如何将这些数字存储到链接列表中,我了解链接列表,但是在.dat看起来像

的情况下
410000 1905 7 50
410001 2015 3 25 
410023 1857 12 

如果最后一行只有3个值,我不确定如何获得这些值。我原来的是。

while(filename >> location >> year >> month >> temp) 

但是我想知道该行上只有3个值,我会遇到错误还是会从下一行中删除温度值,而且由于我认为这不起作用,我想知道Getline如何工作,所以我认为也许我可以尝试

while ( getline(filename,location,year,month,temp)) 

我想知道,如果循环以3个值而不是4个值命中线时会发生什么。因此,如果有人可以解释我如何解决这个问题,那么任何帮助都将受到赞赏。

如果行上只有3个值,我必须告诉用户有错误,但是请继续检查所有其他值,我不能只返回0;并退出程序。

getline()读取istream的完整行。您的循环看起来像:

string line;  
while (getline(file,line)) {
    // parse the string in line to extract the compnents
    ... 
}

分解line的一种方法是使用stringstream

    stringstream is(line);  
    is >> location >> year >> month >> temp; 

如果以行格式发生错误,则is的状态将相应更改。

最新更新