我的代码旨在告诉用户输入的字符串是否是 c++ 中的关键字。 我正在将文件中的关键字读入一个集合中,然后检查用户提供的字符串是否在其中。
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
set<string> key;
fstream fs;
string b;
fs.open("keywords.txt",fstream::in);
while(getline(fs,b))
key.insert(b);
b.clear();
for(auto x:key)
cout << x << endl;
cout << "Enter String user\nPress exit to terminate\n";
while(getline(cin,b))
{
if(b == "exit")
break;
if(key.find(b) != key.end())
cout << "This is a keyword\n";
else
cout << "This is a not a keyword\n";
b.clear();
}
fs.close();
}
keywords.txt文件只是一个关键词列表,可以获取from here
问题是我的程序正确读取了所有关键字,但对于其中一些关键字,例如 false,public,它无法在集合中找到它们。
即当我输入 false 作为用户输入时 它说,“这不是关键字。”
最佳答案
考虑到您的输入文件,我认为您有一些带有尾随空格的关键字名称。
"catch "
"false "
您可以在插入集合之前修剪字符串以删除空格,使用 boost::trim 或您自己的修剪(参见 this question for instance。)
(如果您需要一些关于您的代码的建议:
您可以像这样对输入文件流使用 std::ifstream:
std::ifstream 文件( "keywords.txt");
您不需要在范围内调用 .close(),它会自动完成,感谢 RAII .
您不应该为每个目的重用相同的 std::string 对象,您可以声明新的字符串对象接近它们的使用。你应该给他们更好的名字,比如“line”而不是“b”。这样做,您不需要为字符串调用“.clear()”。
每一行只有一个单词,您可以使用 while(fs>>b) >> 将忽略空格(来自 moldbinlo 和 wangxf 评论)
)
关于c++ - C++ 程序的异常/错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27985166/