我的代码的 C++ 问题

标签 c++ function

<分区>

当我运行它并选择我的号码作为播放器后,计算机返回给我两个输出(而不是一个...)。我不知道为什么,你能帮我解释一下为什么会这样吗?

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

using namespace std;

int random(int a, int b)
{
    int num = a + rand() % (b + 1 - a);
    return num;
}

int main()
{
    srand(time(NULL));

    int myNum;
    cout << "Choose your number, human: ";
    cin >> myNum;

    int min = 1;
    int max = 100;
    int comp;

    string player;

    while(1) {
        comp = random(min, max);
        cout << "Computer: " << comp << endl; // why does this get called twice??
        getline(cin, player);

        if (player == "too high") {
            max = comp - 1;
            cout << "min: " << min << " max: " << max << endl;
        } else if (player == "too low") {
            min = comp + 1;
            cout << "min: " << min << " max: " << max << endl;
        } else if (player == "correct") {
            cout << "Computer found the number..." << endl;
            break;
        }
    }
}

最佳答案

这是因为您正在使用 >>>getline 混合输入。 getline 读取到下一个换行符,>>> 则不会。在你输入你的号码后,还有一个换行符留下,你已经输入了,但还没有被阅读。第一次调用 getline 时,会读取留下换行符的内容,并且程序不会暂停。只有在您第二次调用 getline 时,您的程序才会暂停并等待您输入内容。

解决问题的简单方法是

int myNum;
cout << "Choose your number, human: ";
cin >> myNum;
// flush pending newline
string dummy;
getline(cin, dummy);

关于我的代码的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48597050/

相关文章:

javascript - 如何动态创建一个方法,并将可变数量的参数存储在变量中?

c++ - 在 C++ 中将字符串转换为 char* 时输出格式错误

c++ - 从单词选择中排除字符的方法

c - 在函数中交换两个数组的指针

javascript - 为什么使用设置为方法时函数语句不创建函数?

javascript - 有人可以解释 forEach 循环吗?

c++ - 如何从单链表中删除每第 10 个节点?

c++ - 使用 objective-c 框架的 Swift 项目

c++ - 关闭一个窗口后如何防止Win32应用程序其他窗口变为非事件状态

function - 定义非类私有(private)函数在 Python 中有什么意义吗?