在c++中使用cin.get()从输入流中丢弃不需要的字符
Using cin.get() to discard unwanted characters from the input stream in c++
我正在为我的C++类进行赋值。给出了以下代码。说明说明输入一个六个字符的字符串并观察结果。当我这样做时,第二个用户提示被传递,程序结束。我很确定这是因为第一个cin.getline()在输入流中留下了额外的字符,这会打乱第二个cin.get()的出现。我将使用cin.get、循环或两者来防止额外的字符串字符干扰第二个cin.getline()函数。
有什么建议吗?
#include <iostream>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
你说得对。换行符在第一次输入后保留在输入缓冲区中。
第一次阅读后尝试插入:
cin.ignore(); // to ignore the newline character
或者更好的是:
//discards all input in the standard input stream up to and including the first newline.
cin.ignore(numeric_limits<streamsize>::max(), 'n');
为此,您必须使用#include <limits>
标头。
编辑:尽管使用std::string会更好,但以下修改后的代码仍然有效:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = ' ';
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = ' ';
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
相关文章:
- 如何忽略输入流中的某些字符?
- C++输入流.与 cin unget() 函数有点混淆
- 从输入流中读取行,并能够跳过块
- 使用 Visual Studio 代码读取 C++ 中的输入流时出错
- 为什么我不能从结构将数据输入到字符数组中?
- 处理输入流运算符>>中的无效输入
- 如果用户输入的字符过多,则创建错误消息
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 树莓派上的端口音频,找不到输入流的设备
- 循环直到输入特定字符 (C++)
- 如何将C++输入流分隔符包含在结果令牌中
- 如果两个输入流相等,我如何构造主()到输出是
- C ++读取用户输入的字符一个一个符号
- CIN是否将输入流中的无效字符取用
- 为什么输入流从第二行输入中删除一些字符
- 从输入流中获取下一个字符而无需存储
- 在c++中使用cin.get()从输入流中丢弃不需要的字符
- 如何读取存储在输入流缓冲区中的字符数
- 一次从输入流读取一个单词到字符数组
- 为什么我只能对输入流的前两个字符进行xor解密