我目前正在开发一个程序,该程序从文件中读取每一行并使用特定的分隔符从该行中提取单词。
基本上我的代码是这样的
#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/