c++ - 这个 cin.getline() 行为是什么?

标签 c++

我不是在寻找替代方案,只是想了解为什么 C++ 会这样做。

字符名称[25];

cin.getline(名字, 25);

例如,如果我超过了 getline 的“25”输入限制,为什么它会这样做但匆忙完成程序,它不会为任何 cin.get() 停止,是否与 failbit 标志有关?

#include <iostream>
#include <cstring> // for the strlen() function

using namespace std;

int main()
{

char defName[25];
char name[25];

for (int x = 0; x < 25; x++)
{
    if (x != 24)
    defName[x] = 'x';
    else
    defName[x] = '\0';
}



cout << "Default Name: " << defName << endl << endl;

cout << "Please enter a name to feed into the placeholder (24 Char max): ";

cin.getline(name, 25);

name[24] = '\0';

cout << "You typed " << name << endl;
cin.get();

for (int i = 0; i < strlen(name); i++)
    if (name[i] != ' ')
    {
{
    defName[i] = name[i];
}
    }


cout << "Placeholder: " << defName;

    cin.get();
return 0;
}

最佳答案

does it have to do with a failbit flag?

确实,如果输入对于缓冲区来说太长,就会设置failbit。您可以检查一下:

if (!cin.getline(name, 25)) {
    cout << "Too long!\n";
}

并且,如果您想继续,请使用 cin.clear() 清除它,并使用 cin.ignore(-1) 删除未读字符。

关于c++ - 这个 cin.getline() 行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884300/

相关文章:

c++ - 我应该在调用 pdpotri() 之前设置屏障吗?

C++ 使用迭代器引用连续值

c++ - 是否可以创建一个容器来保存三种数据类型中的一种,并且可以通过单个界面进行查询?

c++ - `signed int` 和 `unsigned int` 之间的加法

C++ 将二维数组传递给函数

java - 在 C++ 中的 java 中的接口(interface)?

c++ - Arduino逐行读取SD文件C++

c++ - 算法移动数组元素

C++ 基类未定义

c++ - Visual C++ 2010 和 native 可执行文件