c++ - 未读行中的最后一个字

标签 c++ delimiter line-endings csv

我目前正在开发一个程序,该程序从文件中读取每一行并使用特定的分隔符从该行中提取单词。

基本上我的代码是这样的

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argv, char **argc)
{
  ifstream fin(argc[1]);
  char delimiter[] = "|,.\n ";
  string sentence;

  while (getline(fin,sentence)) {
     int pos;
     pos = sentence.find_first_of(delimiter);
     while (pos != string::npos) {
        if (pos > 0) {
           cout << sentence.substr(0,pos) << endl;
        }
          sentence =sentence.substr(pos+1);
          pos = sentence.find_first_of(delimiter);
      }
  }
}

但是我的代码没有读取行中的最后一个字。例如,我的文件看起来像这样。 Hello World

程序的输出只是单词“hello”而不是“world”。我已经使用 '\n' 作为分隔符,但为什么它不起作用?

如有任何提示,我们将不胜感激。

最佳答案

getline 不保存字符串中的换行符。例如,如果您的文件包含以下行 “ Hello World \n” getline 将读取此字符串 “ Hello World \0” 所以你的代码错过了“世界”。

忽略那句话没有定义,你可以改变你的代码这样工作:

#include<iostream>
#include<fstream>
using namespace std;

int main(int argv, char *argc)
{
  ifstream fin(argc[1]);
  char delimiter[]="|,.\n ";
  while (getline(fin,sentence)) {
     sentence += "\n";
     int pos;   
     pos = find_first_of(sentence,delimiter);
     while (pos != string:: npos) {
        if (pos > 0) {
           cout << sentence.substr(0,pos) << "\n";
        }
          sentence =sentence.substr(pos+1);
          pos = find_first_of(sentence,delimiter);
      }
  }
}

请注意,我借用了 Bill the Lizards 更优雅的附加最后一个定界符的解决方案。我以前的版本有一个循环退出条件。

关于c++ - 未读行中的最后一个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/872656/

相关文章:

c++ - 如何创建在不同文件中相互使用的类?

c++ - 将 char 绑定(bind)到枚举类型

C++ : getline() function does not include last character/string when reading from a file

Java - 将输入文件中的数字存储在二维数组中

linux - 为什么在 Windows > 8 上使用 CR LF 保存文件?

git - 如何阻止 Git 在本地文件中插入回车符?

c++ - 为什么在 Visual Studio 2008/2010 中_不需要 typename?

c++ - 什么是 Node * 和 aNode?

C++ 字符串和分隔符

python - 删除字符串中重复的换行符