【发布时间】:2016-09-01 19:04:35
【问题描述】:
我在从包含以空格分隔的单词和随机换行的文件中读取时遇到问题。这是我的代码:
vector<string> _vecIgnoreWords;
vector<string> _vecHungerGames;
void readTextFile(char *fileNameHungerGames, vector<string>& _vecHungerGames){
ifstream fileInHungerGames;
string newline;
fileInHungerGames.open(fileNameHungerGames);
if(fileInHungerGames.is_open()){
while(getline(fileInHungerGames, newline)){
stringstream iss(newline);
while(iss){
iss >> newline;
if(!(isCommonWord(newline, _vecIgnoreWords))){
_vecHungerGames.push_back(newline);
cout << newline << endl;
}
}
}
fileInHungerGames.close();
}
main 中的调用:
string fileName = argv[2];
string fileNameIgnore = argv[3];
char* p = new char[fileNameIgnore.length() + 1];
memcpy(p, fileNameIgnore.c_str(), fileNameIgnore.length()+1);
getStopWords(p, _vecIgnoreWords);
char* hungergamesfile_ = new char[fileName.length() + 1];
memcpy(hungergamesfile_, fileName.c_str(), fileName.length()+1);
readTextFile(hungergamesfile_, _vecHungerGames);
停用词无效:
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){
ifstream fileIgnore;
string line;
fileIgnore.open(ignoreWordFileName);
if(fileIgnore.is_open()){
while(getline(fileIgnore, line)){
_vecIgnoreWords.push_back(line);
}
}
fileIgnore.close();
return;
}
我目前的问题是我的这段代码的输出结果如下:
bread
is
is
slipping
away
take
我不确定为什么在使用字符串流时会出现重复(is is)和空行?
我的输出应该是这样的:
bread
is
slipping
away
from
me
同样不那么重要,但我的 while 循环循环次数过多,这就是为什么我有 if(_vecHungerGames.size() == 7682) 有没有办法解决这个循环循环次数过多的问题?
文件示例:
bread is
slipping away from me
i take his hand holding on tightly preparing for the
【问题讨论】:
-
请将输入文件的示例添加到您的帖子中。
-
该文件非常长(整个饥饿游戏书籍之一),但这里是其中一部分的示例:
-
面包从我身边溜走,我拉着他的手紧紧握着准备着
-
@andrewfay 请发布minimal reproducible example 以重现您的问题。
-
欢迎来到 StackOverflow,但你为时过早。首先尝试debugging。如果失败,请在此处寻求帮助。