我编写了此程序并在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:
答案 0 :(得分:1)
根据__fpurge的文档:
在调用
__fpurge()
之后,如果当前正在读取流,则将从系统读取但尚未呈现给应用程序的所有数据都将被丢弃。
因此,从__fpurge(stdin);
函数中删除语句func()
。
答案 1 :(得分:0)
停止清除输入。您已经在主循环中获取了wwchar,因此在调用func()之前已经等待输入。只需删除
__fpurge(stdin);
来自func()