【问题标题】:The last word in line not read行中的最后一个单词未读
【发布时间】:2009-05-16 15:44:13
【问题描述】:

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

所以基本上我的代码是这样的

#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" 。我使用'\n'作为分隔符,但为什么它不起作用?。

任何提示将不胜感激。

【问题讨论】:

  • 这听起来像是课堂作业。
  • 显然不是真正的代码——“句子”的定义在哪里。
  • 我修复了这个问题,但以后请发布符合描述的代码。您最初发布的内容甚至没有编译。如果您发布说明您正在谈论的错误的工作代码,它将为我们节省一些时间并为您提供更快的答案。
  • 谢谢,我现在做错了什么。感谢您的帮助

标签: c++ delimiter line-endings csv


【解决方案1】:

getline 不会在字符串中保存换行符。例如,如果您的文件包含以下行 “你好世界\n” getline 将读取此字符串 “你好世界\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 更优雅的解决方案,即附加最后一个分隔符。我以前的版本有一个循环退出条件。

【讨论】:

    【解决方案2】:

    转述this reference document

    字符被提取,直到找到分隔字符 (\n),丢弃并返回剩余的字符。

    您的字符串不是以\n 结尾,而是^`hello world`$,因此没有找到分隔符或新的位置。

    【讨论】:

    • 在这种情况下是否有任何其他分隔符可用于识别行尾?
    • 或者我可以使用 getline 以外的代码来读取 \n 吗?如果有,那是什么?
    • 我猜你错过了这篇文章; '如果你不想提取这个字符,你可以使用成员“get”代替。'
    【解决方案3】:

    正如其他人所提到的,getline 不会在末尾返回换行符。修复代码的最简单方法是在 getline 调用之后将一个附加到句子的末尾。

    #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)) {
         sentence += "\n";
         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);
          }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      相关资源
      最近更新 更多