c++ - 尺寸较大的 cin.getline( )

标签 c++ getline

#include<iostream>
using namespace std;

int main()
{
   char test[10];
   char cont[10];

   cin.getline(test,10);
   cin.getline(cont,10);

   cout<<test<<" is not "<<cont<<endl;
    return 0;
}

当我输入时:

12345678901234567890

输出是:

123456789

cont 似乎是空的。谁能解释一下?

最佳答案

如果输入太长,

istream::getline 会设置失败位,从而阻止进一步的输入。将您的代码更改为:

#include<iostream>
using namespace std;

int main()
{
   char test[10];
   char cont[10];

   cin.getline(test,10);
   cin.clear();                    // add this
   cin.getline(cont,10);

   cout<<test<<" is not "<<cont<<endl;
    return 0;
}

关于c++ - 尺寸较大的 cin.getline( ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6053957/

相关文章:

具有严格所有权语义的 C++ vector

c++ - SDL - 窗口数据

c++ - 从连续内存中的对象创建链表

c++ - 打开文本文件并读取带有空格的字符串,然后将 2 个单独的整数放入结构中

c++ - 在 C++ 中使用 setInterval()

c++ - 返回 & 和不返回有什么区别?

c - 输入返回正确的字符串但不运行函数

c++ - 使用 std::getline() 读取一行?

c++ - 使用 getline 获取字符串对象

c++ - C++ 类中的 Getline