我有一个问题从一个文件中读取,该文件中有空格分隔的单词,并且随机添加新行。这是我的代码:
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();
}
主要电话:
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
答案 0 :(得分:1)
尝试更像这样的事情:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
std::vector<std::string> _vecIgnoreWords;
std::vector<std::string> _vecHungerGames;
void getStopWords(const char *filename, std::vector<std::string>& output)
{
std::ifstream file(fileName);
std::string s;
while (std::getline(file, s))
output.push_back(s);
}
void readTextFile(const char *filename, std::vector<std::string>& output)
{
std::ifstream file(fileName);
std::string s;
while (file >> s)
{
if (!isCommonWord(s, _vecIgnoreWords))
{
output.push_back(s);
std::cout << s << std::endl;
}
}
}
int main()
{
getStopWords(argv[3], _vecIgnoreWords);
readTextFile(argv[2], _vecHungerGames);
// use _vecHungerGames as needed...
return 0;
}