首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何清除cin输入缓冲区

如何清除cin输入缓冲区
EN

Stack Overflow用户
提问于 2022-11-17 19:33:50
回答 1查看 81关注 0票数 -1
代码语言:javascript
运行
复制
int main() {
    string inputName;
    int age;
    // Set exception mask for cin stream
    cin.exceptions(ios::failbit);

    cin >> inputName;
    while (inputName != "-1") {
        // FIXME: The following line will throw an ios_base::failure.
        //        Insert a try/catch statement to catch the exception.
        //        Clear cin's failbit to put cin in a useable state.

        try
        {
            cin >> age;
            cout << inputName << " " << (age + 1) << endl;
        }

        catch (ios_base::failure& excpt)
        {
            age = 0;
            cout << inputName << " " << age << endl;
            cin.clear(80, '\n');

        }

        inputName = "";

        cin >> inputName;

    }

    return 0;
}

捕获异常后,我无法清除cin,甚至试图将变量设置为空字符串.我的程序在cin >> inputName上停止;在异常被捕获后,我认为cin.clear(80,'\n');重置cin并将其置于可用状态?

调试器告诉我,当我尝试将另一个字符串输入到inputName变量时,存在一个未处理的异常。任何帮助都是非常感谢的,谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-17 19:48:42

我不太明白你想修什么。无论如何,我只是解决了清洁cin的问题。

代码语言:javascript
运行
复制
#include <iostream>
#include <limits>

using namespace std;

int main() {
    string inputName;
    int age;
    
    // Set exception mask for cin stream
    cin.exceptions(ios::failbit);
    
    cout << "Input name: ";
    cin >> inputName;
    while (inputName != "-1") {
        // FIXME: The following line will throw an ios_base::failure.
        //        Insert a try/catch statement to catch the exception.
        //        Clear cin's failbit to put cin in a useable state.
        try {
            cout << "Age: ";
            cin >> age;
            cout << inputName << " " << (age + 1) << endl;
            break;
        }
        catch (ios_base::failure& except) {
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    return 0;
}

如您所见,我不向cin.clear()传递任何参数,因为这个方法只是cin中的resets the state flags。要清空cin buffer,您必须使用cin.ignore()传递的两个参数,第一个参数是size of the buffer,在本例中,我使用cin.ignore()来指定它,而第二个参数是告诉它end character是什么。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74481147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档