<分区>
标签 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;
最佳答案
这是读取 int
/long
/float
/etc 之后的字符串输入的常见问题。问题是读取整数后缓冲区中剩余的 '\n'
字符:
cin >> maximumSnowfall;
当您调用 getline
时,仍然保留在缓冲区中的 '\n'
会立即被读取。标准库将其解释为空字符串,并立即返回。
要避免此问题,请在读取 int
后调用 ignore
:
cin >> maximumSnowfall;
cin.ignore(1, '\n');
关于c++ - cin.getline 不等待 rand 上的输入和设置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35382436/