如何用字符终止整数输入循环?

How to terminate an integer-input loop with a character?

Stack 和 C++ 的新手。 我想终止一个循环,该循环用一个字符反刍输入给它的数字。说,Q 退出。以下程序可以正常运行并且没有语法错误。如何在不编辑输入参数的情况下终止此循环?

#include <iostream>
#include <string>

using namespace std;

int main()
{

    bool run = true;

    while(run)
    {
    cout<<"Enter your two favorite numbers."<<endl;

    int num1;
    int num2;

    cin>>num1>>num2;

    cout<<"You entered "<<num1<<" and "<<num2<<"."<<endl;

    }

    return 0;

}

您想要 break statement。但是您还需要为第一个输入读取一个字符串,而不是一个整数。

while(run)
{
    cout<<"Enter your two favorite numbers, or 'Q' to exit."<<endl;

    string input;
    int num1;
    int num2;

    cin>>input1;

    if (input == "Q")
    {
        break;
    }
    else
    {
        num1 = stoi(input);
    }

    cin>>num2;

    cout<<"You entered "<<num1<<" and "<<num2<<"."<<endl;
}