如何cin文本

时间:2013-03-02 15:48:52

标签: c++ text cin

如何让用户在此程序中输入文本而不是数字。 我能获得cin声明接受文字吗?我必须使用char吗?

int main()
{
    using namespace std;
    int x = 5;
    int y = 8;
    int z;
    cout << "X=" << x << endl;
    cout << "Y=" << y << endl;
    cout << "Do you want to add these numbers?" << endl;
    int a;
    cin >> a;
    if (a == 1) {
        z = add(x, y);
    }
    if (a == 0) {
        cout << "Okay" << endl;
        return  0;
    }
    cout << x << "+" << y << "=" << z << endl;
    return 0;
}

--- --- EDIT 为什么这不起作用?

int main()
{
    using namespace std;
    int x = 5;
    int y = 8;
    int z;
    cout << "X = " << x << " Y = " << y << endl;
    string text;
    cout << "Do you want to add these numbers together?" << endl;
    cin >> text;
    switch (text) {
        case yes:
            z = add(x, y);
            break;
        case no: cout << "Okay" << endl;
        default:cout << "Please enter yes or no in lower case letters" << endl;
            break;
}
    return 0;
}

谢谢大家! 如果您有兴趣,可以查看我在这里制作的游戏。 http://pastebin.com/pmCEJU8E 你正在帮助一个年轻的程序员实现他的梦想。

3 个答案:

答案 0 :(得分:2)

您可以将std::string用于此目的。请记住,cin会将您的文字读取到空格。如果要从同一个库中读取整行使用getline函数。

答案 1 :(得分:1)

您可以使用std::string

std::string str;
std::cin>>str; //read a string 

// to read a whole line
std::getline(stdin, str);

答案 2 :(得分:0)

由于您只关注来自用户的1个字符响应,如Do you want to add these numbers?可能会被(Y/N)连接起来,您应该(在我看来)使用getchar()函数有意只读一个字符。这就是我将如何处理容易出错的1字符输入处理:

bool terminate = false;
char choice;
while(terminate == false){
    cout << "X=" << x << endl;
    cout << "Y=" << y << endl;
    cout << "Do you want to add these numbers?" << endl;

    fflush(stdin);
    choice = getchar();
    switch(choice){
    case 'Y':
    case 'y':
        //do stuff
        terminate = true;
        break;
    case 'N':
    case 'n':
        //do stuff
        terminate = true;
        break;
    default:
        cout << "Wrong input!" << endl;
        break;
    }
}

作为对您的修改的回复

这不起作用,因为您无法将std::string作为参数传递给switch。正如我告诉过你的那样,你应该只读一个角色。如果您坚持使用字符串,请不要使用switch,而是使用字符串比较器if else转到==块。

cin >> text;
if(text == "yes"){
    z = add(x, y);
}
else if(text == "no")
{
    cout << "Okay" << endl;
}
else
{
    cout << "Please enter yes or no in lower case letters" << endl;
}