cin.getline不等待rand上的输入和设置参数

时间:2016-02-13 16:38:43

标签: c++

我只是试图从用户那里得到滑雪胜地名称的输入,以完全显示空白区域。我尝试过多种方法,包括使用cin.get和cin.getline设置大小常量。因此没有运气。同样在它下面,我试图使用用户先前在minimumSnowfall和maximumSnowfall中输入的信息在rand函数上设置参数。

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>

using namespace std;


int main(void)

{
    int minimumSnowfall;
    int maximumSnowfall;
    char skiResortName[81];


    cout << "I will forecast how much snowfall there will be on each \nday this weekend. You get to pick the range. " << endl;

    cout << "Please enter the minimum amount of snow that \nwill fall in one day in inches: ";
    cin >> minimumSnowfall;


    cout << "Please enter the maximum amount of snow that \nwill fall in one day in inches: ";
    cin >> maximumSnowfall;

    // need to fix to display names with white spaces
    cout << "Enter the name of the ski resort: ";
    cin.getline(skiResortName,81);
    cout << "The local forecast for snowfall at " << skiResortName << " this weekend: " << endl;

    // need to fix to display random number using parameters entered by weatherman in minimumSnowfall and maximumSnowfall
    cout << "Friday: " rand  (minimumSnowfall, maximumSnowfall);







    return 0;

1 个答案:

答案 0 :(得分:2)

这是在int / long / float /等之后读取字符串输入的常见问题。问题是读取整数后缓冲区中剩余的'\n'字符:

cin >> maximumSnowfall;

当您致电getline时,仍会保留缓冲区中的'\n'。标准库将其解释为空字符串,并立即返回。

要避免此问题,请在阅读ignore后致电int

cin >> maximumSnowfall;
cin.ignore(1, '\n');