行中最后一个字未读
我目前正在开发一个程序,该程序从文件中读取每一行并使用特定分隔符从该行中提取单词。
所以基本上我的代码看起来像这样
#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' 作为分隔符,但为什么它不起作用?
任何提示将不胜感激。
I am currently working on a program that read each line from a file and extract the word from the line using specific delimiter.
So basically my code looks like this
#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);
}
}
}
However my code didnot read the last word in the line. For example, my file looks like this.
hello world
the output from the program is only the word "hello" but not "world" . I have use '\n' as the delimiter but why didnot it works?.
Any hint would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getline 不保存字符串中的换行符。 例如,如果您的文件包含以下行
“你好世界\n”
getline 将读取这个字符串
“你好世界\0”
所以你的代码错过了“世界”。
忽略未定义的句子,您可以更改代码以如下方式工作:
注意,我借用了 Bill the Lizards 更优雅的解决方案,即附加最后一个分隔符。 我以前的版本有一个循环退出条件。
getline does not save the new line character in the string. For example, if your file has the line
"Hello World\n"
getline will read this string
"Hello World\0"
So your code misses the "World".
Igonoring that sentence is not defined, you could alter your code to work like this:
Note, I borrowed Bill the Lizards more elegant solution of appending the last delimiter. My previous version had a loop exit condition.
解释此参考文档:
提取字符直到分隔字符(
\n
) 被发现,被丢弃并返回剩余的字符。您的字符串不是以
\n
结尾,而是^`hello world`$
,因此找不到分隔符或新的 pos。Paraphrasing this reference document:
Characters are extracted until the delimiting character (
\n
) is found, discarded and the remaining characters returned.Your string doesn't end with an
\n
, it is^`hello world`$
, so no delimiter or new pos is found.正如其他人提到的, getline 在末尾不返回换行符。 修复代码的最简单方法是在 getline 调用之后在句子末尾添加 1。
As others have mentioned, getline doesn't return the newline character at the end. The simplest way to fix your code is to append one to the end of the sentence after the getline call.