【问题标题】:using str.find() to see if a particular letter is in a word使用 str.find() 查看特定字母是否在单词中
【发布时间】:2016-03-20 23:21:13
【问题描述】:

我正在为学校制作一个刽子手游戏。 要猜测的单词是从数据文件中提取的, 程序从文件中选择最后一个单词作为游戏使用的单词, 'words' 是我用于此的变量, 随着游戏的进行,用户猜测一个字母,如果该字母在单词中,则为正确,否则为不正确,程序逐渐显示“板”或刽子手的图片。

我用str.find()查看猜到的字母是否在单词中,代码如下:

while (wrongGuess < 7){
    cout << "\nGuess a letter in the word: " << endl;
    cin >> guess;

    if (words.find(guess)==true){
        cout << "Correct! " << guess << " is FOUND in the word " << word << endl;
        continue;}
    else
        {cout << guess << " is NOT FOUND in the word " << endl;
        wrongGuess++;
        if(wrongGuess == 1)
            cout << board2;
        else if(wrongGuess == 2)
            cout << board3;
        else if(wrongGuess == 3)
            cout << board4;
        else if(wrongGuess == 4)
            cout << board5;
        else if(wrongGuess == 5)
            cout << board6;
        else if(wrongGuess == 6)
            cout << board7 << "\nSorry Game Over";
        }

使用的词是programming

我的问题是有时当我输入一个正确的字母(如r)时,它告诉我我是对的,有时我输入一个不同的正确字母(p)并且程序告诉我我错了。

我有什么问题?

【问题讨论】:

  • words.find(guess)==true -- 但 string::find 返回位置,而不是真/假...
  • 还可以考虑使用“string the STL container”接口(带有std::find)而不是成员函数;该接口比字符串的成员函数更符合语言的其余部分

标签: c++


【解决方案1】:

std::basic_string::find 又名。 std::string::find 返回给定字符在字符串中的位置,而不是 bool

您发布的代码有时会起作用,因为true 衰减为1,如果搜索到的字符位于位置 1,则条件为真。

要修复它,您应该这样做:

...
if (words.find(guess)!=std::string::npos){
    ...

std::basic_string::find

【讨论】:

    【解决方案2】:

    使用std::string::npos 来检查find 的结果。

     if( words.find(guess) != std::string::npos)
     {
        //...
     }
     else
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2020-04-14
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多