c++ - 当我超过第一个 getline() 的输入数组大小时,第二个 getline 或其他输入函数不起作用

标签 c++ getline

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

int main() 
{
char d,a[9],e[9];

cin.getline(a,9);
cin.getline(e,9);
cin>>d;
puts(a);
puts(e);
cout<<d<<endl;
return 0}

当我在输出屏幕上输入“大家好”时,puts(e)打印一个空行,d 打印一个随机字符。second getline功能和cin由于第一个 getline,功能无法正常工作.提前致谢。

最佳答案

你应该读一些documentation对于你使用的东西:

After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):
- [...]
- count-1 characters have been extracted (in which case setstate(failbit) is executed).

(强调我的)

因此,如果输入太长,第一个 getline 将失败,从而使 std::cin 处于不良(即不可读)状态。这使得所有连续的输入操作立即失败。


备注:为了避免大量丑陋的麻烦,您应该避免使用 C 风格的字符串和“某种 C 风格”成员-getline,而只使用 std::string和非成员(member)std::getline相反。

关于c++ - 当我超过第一个 getline() 的输入数组大小时,第二个 getline 或其他输入函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34295034/

相关文章:

c++ - 静态常量字符串(类成员)

c++ - ifstream getline 问题

c++ - getline 函数不工作

c++ - std::shared_ptr 为 null 但不为空

c++ - 构建 XPCOM XULRunner 2.0 或更新版本

c++ - 为什么在异常掩码未设置为 eofbit 时 getline() 抛出 'std::ios_base::failure'?

c++ - 使用 getline 将字符串存储在数组中

c++ - 在 C++ 中使用 getline() 时没有从文本文件中获取所有行

c++ - 使用 JNIEnv::FindClass:我需要释放返回的 jclass 引用吗?

c++ - 如何将 C++ 控制台输出保存在文本文件中?