C++程序的异常/错误行为

Joh*_*son 1 c++ string set

我的代码旨在告诉用户输入的字符串是否是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();
}
Run Code Online (Sandbox Code Playgroud)

keywords.txt文件只是一个关键字列表,可以从这里获得

问题是我的程序正确读取所有关键字,但对于其中一些如false,public它无法在集合中找到它们.

即,当我输入false作为用户输入时,它说"这不是关键字".

Nik*_*kko 6

考虑到您的输入文件,我认为您有一些带有尾随空格的关键字名称.

"catch       "
"false         "
Run Code Online (Sandbox Code Playgroud)

您可以在插入集合之前修剪字符串以删除空格,使用boost :: trim或您自己的修剪(例如,请参阅此问题.)

(如果您需要一些关于代码的建议:

  • 您可以像这样使用std :: ifstream作为输入文件流:

    std :: ifstream文件("keywords.txt");

  • 您不需要在范围之后调用.close(),它将由RAII自动完成.

  • 您不应该为每个目的重用相同的std :: string对象,您可以声明接近其使用的新字符串对象.你应该给他们更好的名字,比如"line"而不是"b".这样做,你不需要为你的字符串调用".clear()".

  • 每行只有一个单词,你可以使用while(fs >> b)>>将忽略空格(来自moldbinlo和wangxf评论)

)

  • @RubixRechvin:`std :: getline(stream,line); boost :: trim(line);`应该很棒! (3认同)