c++ - 刷新 cin 输入的正确方法

标签 c++ input whitespace cin getline

#include <iostream>
using namespace std;

int a, b, c, d;

void main()
{
    cout << "Reading a" << endl;
    cin.ignore();
//  cin.clear();
    cin >> a;

    cout << "Reading b" << endl;
    cin.ignore();
//  cin.clear();
    cin >> b;

    cout << "Reading c" << endl;
    cin.ignore();
//  cin.clear();
    cin >> c;

    cout << a << " " << b << " " << c << endl;
    system("pause");
}

我从 a 到 c 读取了 3 次变量。当我输入随机数然后不使用空格(234566)接受它时,它会正常工作。但是,当我的输入看起来像这样 23 45 66(中间有空格)时,它会立即将 23 放入 a45b66c

我的意图是读取数字,以空格结束,然后忘记输入的其余部分并再次读取到下一个变量。

cin.ignore()cin.clear() 似乎对我没有帮助,但可能是我用错了。

我可以创建自己的缓冲区,然后检查它是否有空格,但在此之前我想看看是否有其他方法。

最佳答案

mikedu95 在评论中回答:

Read a whole line with getline, then perform string to integer conversion using stoi

#include <string>
#include <iostream>
using namespace std;

string str;
int a, b, c, d;

void main()
{
    cout << "Reading a" << endl;
    getline(cin, str);
    a = stoi(str);

    cout << "Reading b" << endl;
    getline(cin, str);
    b = stoi(str);

    cout << "Reading c" << endl;
    getline(cin, str);
    c = stoi(str);

    cout << a << " " << b << " " << c << endl;
    system("pause");
}

关于c++ - 刷新 cin 输入的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774742/

相关文章:

c++ - 为什么VC++/MFC没有main函数?

c++ - 删除集合迭代器值并递增迭代器

c++ - 何时用单例替换全局 std::unique_ptr

grails - 为什么 grails 在表单中添加一个隐藏的复选框——它的用途是什么?

javascript - 从 input.value 添加对象属性

emacs - 如何获得 ediff 模式以停止突出显示仅由空格不同的行?

c++ - 整数变量与整数字面量变化乘法结果

html - 如何组合文本转换 :uppercase with "normal" user text?

c - 如何允许使用 scanf 输入空格?

css - 在没有换行符的情况下将 div 环绕在文本周围