使用 getline 从输入文件流中读取字符串和数字

reading strings and numbers from input file stream using getline

我得到了 getline(ifstream foo, string bar) 函数的语法,我知道它的第三个参数是定界符,设置为 '\n'。

我有一个文件要读取,它的第一列和第二列都有数字。 问题是在第三列中,我必须读取可能包含空格的国家名称。

我已经检查过我的代码肯定能成功读取前两列的数字,但是当我的代码尝试读取国家/地区名称时,我收到 'Segmentation fault (cord dumped)' 错误消息。

我的代码如下所示:

string name[50];
double year1[50],year2[50];
fstream ifstr;
ifstr.open("thefile.csv");
for (int i=0; (!(ifstr.eof())) || i < 51; i++) {
ifstr >> year1[i] >> year2[i];
getline(ifstr, name[i]);} // expecting this line to be reading/storing
//anything that comes after 3rd column into string array

我分配的给定变量太长太复杂,所以我把它写下来以提高可读性,但那一行几乎是问题所在。

根据说明 sheet,我的教授提到

Reading the populations is straightforward, and can be done using the standard file IO functions we covered in class (i.e., ">>" using an input stream). However, since the names of some countries contain spaces, we need to use getline instead of >> for the name field. Fortunately, the country is the final field so we can use ">>" to read the populations and then a getline to finish the line. You will need to input data until the end of file is reached. Recall that getline's return value is false if at end of file, so its easy to check for this.

我查找了有关此主题的所有可用资源,但到目前为止我找不到解决此问题的资源。

请指教

你的循环条件是错误的。您应该只在 both 这些值都为真时循环。如果其中任何一个变为假,你应该停止。所以 || 实际上应该是 &&.

你也遇到了超出范围的问题。条件 i < 51 错误。 i 的值为 50 将在索引时溢出数组。所以正确的条件是i < 50.

最后,eof 不是导致您停止阅读的流中唯一的条件。只需使用流的 bool 运算符即可。

for( int i = 0; ifstr && i < 50; i++ )