【发布时间】: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