【发布时间】:2016-12-05 08:58:29
【问题描述】:
代码的目的是基本上删除文本文件中存在的无用数组中的单词。我遇到了一个非常奇怪的问题,代码不会删除短语“waiting on the Shelf”中的“the”一词,但所有其他测试用例(很多)都通过了。有什么想法吗?
int main(){
string useless[20] = { "an", "the" , "of", "to", "and", "but", "nor", "or", "some", "any", "very", "in", "on", "at", "before", "after", "into", "over", "through", "along"};
ifstream fin("input.txt");
if(fin.fail()){
cout << "Input failed to open" << endl;
exit(-1);
}
string line;
getline(fin, line);
getline(fin, line);
getline(fin, line);
getline(fin, line);
ofstream fout("output.txt");
while(getline(fin, line)){
vector<string> vec;
istringstream iss(line);
while (iss) {
string word;
iss >> word;
transform(word.begin(), word.end(), word.begin(), ::tolower);
vec.push_back(word);
}
for(int i = 0; i < vec.size(); i++){
for(int j = 0; j < 20; j++){
if(vec[i] == useless[j]){
vec.erase(remove(vec.begin(), vec.end(), vec[i]), vec.end());
}
}
fout << vec[i] << " ";
}
fout << endl;
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
是的,是的,我可以看到调试器将如何真正帮助我。我目前没有使用任何 IDE(只是 sublime 和终端),因此缺少调试器。
-
您不需要 IDE 即可使用调试器 - 您只需从命令行使用 gdb。
-
通过将
main中的内容拆分为两个或三个函数,在代码中添加更多结构也是一个好主意。
标签: c++ string vector token erase