3

我编写了一个简单的游戏。我知道如何使用 cout/cin,但遇到 printf/scanf 问题。下面的代码适用于 cout/cin。问题是,如何将它们转换为 printf/scanf?为什么评论中的代码不起作用?

编辑:我的意思是如果我删除 cout/cin 行,而当我使用 printf/scanf 时,它就不能正常工作。

#include <iostream>
#include <time.h>

using namespace std;

int main()
{
    srand(time(NULL));
    int min=0, max=1000, guess, counter=0;
    bool winner=false;
    char answer;

    while(counter<10){
        guess = rand()%(max-min)+min;
        // printf("Did you pick %d? \t", guess);
        // scanf("%c", &answer);
        cout << "Did you pick " << guess << "?\t";
        cin >> answer;
        if(answer=='y'){ // yes
            winner=true;
            // printf("Computer wins.\n");
            // printf("You picked: %d", guess);
            cout << "Computer wins." << endl;
            cout << "You picked: " << guess;
            break;
        }
        else if(answer=='m'){ // more
            min=guess;
            counter++;
        }
        else if(answer=='l'){ // less
            max=guess;
            counter++;
        }
    }
    if(winner==false){
        // printf("User wins.\n");
        cout << "User wins." << endl;
    }
    return 0;
}
4

1 回答 1

2

问题是 scanf() 不会从 stdin 中删除换行符 '\n' 字符,因此在下一次迭代中,下一个 scanf() 会读取它并尝试处理它,似乎忽略了输入。
试试这个:

scanf("\n%c", &answer);

这样,您期望换行符和 scanf() 消耗它。

于 2012-11-03T00:21:19.213 回答