c++ - 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:
解决方案
根据__fpurge的文档:
在调用 之后
__fpurge()
,如果流当前正在读取,则任何已从系统读取但尚未呈现给应用程序的数据都将被丢弃。
__fpurge(stdin);
所以从func()
函数中删除语句。
推荐阅读
- java - 如何实现用于写入文本文件的代码(Java)
- firebase - React Native Firebase 只获取一次数据
- javascript - 将文本框中的数字除以 4 组数字,每个数字得到其总和,并组合每组中每个总和的所有最后一位
- swift - Swift 和 AudioFormatGetProperty(_:_:_:_:_:)
- javascript - “震动效果”只持续一个周期
- javascript - 选择表单更改时更改链接参数
- android - AlertDialog dialog.dismiss(), dialog.close() 不工作
- html - 使 flexbox 容器可垂直滚动
- c# - LINQ 方法语法包括 4 层深度
- angular - 使用输入表单Angular更新服务变量?