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

标签 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/

上一篇:c++ - C++中的双指针数组

下一篇:c++ - 将 Qt 添加到现有的 GNU C++ 程序

相关文章:

c++ - 混淆数据地址对齐

c++ - 这里是否为这个模板函数生成了不同的实例?

c++ - 如何将 Dos 的 dbm(数据库文件) 转换为 Csv?

c++ - 是否有一个普遍接受的习惯用法来指示 C++ 代码可以抛出异常?

c++ - 无法使用函数 Cfile 读取 MFC 中文件中的内容?

c++ - 为什么我的 32 位 Fortran/C DLL 不能在 MSYS2 中编译?

c++ - 包含循环类以保持 C++ 的向后兼容性

c++ - 是否传递指针参数,在 C++ 中按值传递?

c++ - 如何编写 C++ 控制台窗口程序

c++ - 加载 DLL 阻塞 UI 线程