C++ getline()分隔符出现问题

C++ getline()分隔符出现问题,c++,string,file,delimiter,getline,C++,String,File,Delimiter,Getline,我试图读取一个文件,并在每一行上获取特定的字符串。我需要的字符串的结尾用分号标记。这样做没有问题,但我注意到带有分隔符的getline()会自动将新行附加到字符串中 filename.open(FileName); while(filename) { getline(filename, name[counter], ';'); filename >> amount[counter] >> unit[counter] >> calori

我试图读取一个文件,并在每一行上获取特定的字符串。我需要的字符串的结尾用分号标记。这样做没有问题,但我注意到带有分隔符的getline()会自动将新行附加到字符串中

 filename.open(FileName);
 while(filename)
  {
    getline(filename, name[counter], ';');

    filename >> amount[counter] >> unit[counter] >> calories[counter];
    counter++;

  }
因此,当我要打印名称数组时,会有一个额外的换行符,我自己没有放在那里,就好像一路上有一个额外的“\n”。有人有解决办法吗?下面是我阅读的文件格式示例

戴夫·琼斯;24高
吉利安·琼斯;短34
等等。

更好的方法是将文件逐行读取到缓冲区中,然后按“;”分割字符串:

while(true) {
    std::string line;
    std::getline( in, line );
    if( !in ) break;
    std::istringstream iline( line );
    while(true) {
        std::string str;
        std::getline( iline, str, ';' );
        if( !iline ) break;
        // you get string by string in str here
    }
}
跑步后

filename >> amount[counter] >> unit[counter] >> calories[counter];
换行符仍在缓冲区中。当您仅使用“>>”时,这通常不是问题;它只是忽略了换行符。但是当您混合使用getline和“>>”时,您需要忽略“>>”留下的新行。试着这样做:

filename >> amount[counter] >> unit[counter] >> calories[counter];
// Ignore first character or everything up to the next newline,
// whichever comes first
filename.ignore(1, '\n'); 

这有点多余,但很容易阅读。

一种更简单的方法来容纳空白:

filename >> amount[counter] >> unit[counter] >> calories[counter] >> std::ws;

您显示的文件格式似乎不匹配
>数量[计数器]>>单位[计数器]>>卡路里[计数器]
。另外,当
计数器+++
超过数组大小时会发生什么情况?