首页 > 解决方案 > C++ 忽略输入字符串

问题描述

我编写了这个程序并在 Ubuntu 中运行它。程序跳过行cin >> str;,不允许我输入字符串。我该如何解决这个问题?

代码:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stdio_ext.h>
using namespace std;

void func()
{
    cout << "Enter a string: ";
    string str;
    __fpurge(stdin);
    cin >> str;
    cout << "Your string: " << str << endl;
    getwchar();
}

int main()
{
    while(true)
    {
        cout << "0. Exit" << endl;
        cout << "1. Enter a string" << endl;
        cout << "----------------------------" << endl;
        char ch = getwchar();
        if(ch == '0') break;
        else if(ch == '1') func();
    }
}

输出:

0. Exit
1. Enter a string
----------------------------
1
Enter a string: Your string: 

标签: c++

解决方案


根据__fpurge的文档:

在调用 之后__fpurge(),如果流当前正在读取,则任何已从系统读取但尚未呈现给应用程序的数据都将被丢弃。

__fpurge(stdin);所以从func()函数中删除语句。


推荐阅读