【问题标题】:I keep getting a space in my program from cin.get()我一直在我的程序中从 cin.get() 获得一个空间
【发布时间】:2015-09-28 11:11:06
【问题描述】:

这是我的程序:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

#define RAND(a,b) (a + rand()% (b-a+1))


int main()
{
    int num; 
    int computer_total = 0, players_total = 0;
    string name;

    srand(time(NULL));

    for(;;)
    {
        cout <<"What's your name? ";
        cin >> name;
        cin.get();
        if(name == "stop")exit(0);

        for(int i =0; i < 5; i++)
        {
            cout << name <<" roll the dice.\n";
            cin.get();                         //skips the cin.get() the first time aroun
            num = RAND(1,6);                   //Also makes akward spacing 
            players_total += num;
            cout <<"You got: " << num << endl;

            cout <<"Now it's the computers turn.\n";
            cin.get();
            num = RAND(1,6); 
            computer_total += num;
            cout <<"Computer got: " << num << endl;
        }

        cout <<"Total of computers dice: " << computer_total << endl;
        cout <<"Total of your dice: " << players_total << endl;

        if(computer_total == players_total)cout <<"Its a tie! \n"; 
        else if(computer_total > players_total)cout <<"Computer won.\n"; 
        else if(computer_total < players_total)cout <<"You won!\n";  
        //Do I need an else here?

    }

    return(0);
}

在我使用cin.get() 时,我在编译程序时会出现尴尬的间距。像这样:

但我需要使用cin.get() 来允许用户为自己和计算机掷骰子。不确定我是否正确使用它。

【问题讨论】:

    标签: terminal compilation c++


    【解决方案1】:

    好吧,如果你按下回车键,它就会一直打印在那里(这就是这条线的来源)。使用一些无回声功能,ncurses 明白了。 哦,关于跳过第一个输入,请在获取之前使用 cin.ignore()。

    //这里需要else吗?

    没有

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 2014-06-06
      • 1970-01-01
      • 2016-12-03
      • 2021-11-25
      相关资源
      最近更新 更多