ecelder之后的c ++ 2 cin.getline

时间:2014-12-13 05:34:02

标签: c++ if-statement cin

在这个游戏中我想让玩家写下他们的名字。但是电脑只接受这个名字。我该怎么办?

输入: 1 短发 嫁

输出: 欢迎来到游戏Bob and, 现在计算机选择了你们中的一个。 所选择的将开始游戏

    #include<cstring>
        #include<iostream>
        using namespace std;
        int main(){
        int choose;
        cin>>choose;
        if(choose==1){
            char name1[30],name2[30];
            cout<<"Hi player 1\nWhat's your name?\n";
            cin.getline(name1,30);
            cout<<"Hi player 2\nWhat's your name?\n";
            cin.getline(name2,30);
            cout<<"Welcome to the game"<<name1<<"and"<<name2<<"Now the Computer chooses one of you.The chosen one will start the game\n\n";  
}  

1 个答案:

答案 0 :(得分:1)

好吧,我稍微更改了你的代码,它运行正常。

#include <string>
#include<iostream>
#include <conio.h>
using namespace std;
int main(){
    int choose;
    cin >> choose;
    if( choose == 1 ){
        string name1, name2;
        cout << "Hi player 1\nWhat's your name?\n";
        cin >> name1;
        cout << "Hi player 2\nWhat's your name?\n";
        cin >> name2;
        cout << "Welcome to the game" << name1 << "and" << name2 << "Now the Computer chooses one of you.The chosen one will start the game\n\n";
    }
    _getch();
    return 0;
}

你没有名字长度的限制。