【问题标题】:Issue with getline() delimitergetline() 分隔符问题
【发布时间】:2013-02-10 05:07:36
【问题描述】:

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

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

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

  }

因此,当我要打印出名称数组时,会有 1 个额外的换行符,而我自己并没有放在那里,就好像一路上有一个额外的 '\n' 被拾取一样。有没有人有办法解决吗?下面是我正在读取的文件格式的示例。

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

【问题讨论】:

  • 您显示的文件格式似乎与>> amount[counter] >> unit[counter] >> calories[counter] 不匹配。另外,当counter++ 超过数组的大小时会发生什么?

标签: c++ string file delimiter getline


【解决方案1】:

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

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
    }
}

【讨论】:

    【解决方案2】:

    运行后

    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'); 
    

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

    【讨论】:

      【解决方案3】:

      吞下空格的更简单方法:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-21
        • 1970-01-01
        • 2014-04-28
        • 2011-04-15
        相关资源
        最近更新 更多