c++ - getline() 和输入流的问题

标签 c++ stream cin getline

代码

#include<iostream>
int main()
{
    char s[20];
    char ch;
    
    std::cin.getline(s,10);
    std::cout<<"x"<<s<<"x"<<"\n";
    
    std::cin>>ch;
    std::cout<<"x"<<ch<<"x";
    
    std::cin>>ch;
    std::cout<<"x"<<ch<<"x";
    
    std::cin>>ch;
    std::cout<<"x"<<ch<<"x";
}

输出1

bonaparte    // I entered these 9 characters as input
xbonapartex
a            //  input
xax
b            // input
xbx
c            // input
xcx

输出2

bonaparte2    // I entered these 10 characters as input
xbonapartex
x x
x x
x x

与第一个输出相比,我刚刚输入了一个额外的字母,这意味着通过键盘 bonaparte2 总共输入了 10 个字符。

据我所知,getline 将提取 9 个字符并添加 '\0' 并存储在字符串 s 中。因此流保留字符 2\n。所以第一个 cin>>ch 应该采用 2 并打印 x2x

现在第二个 cin>>ch 应该忽略 \n 因为它是前导空白字符,但这些都没有发生。程序不要求键盘输入。

最佳答案

std::cin.getline(s,10); ,因为输入大于 stream_size提供,istream::getline将流设置为失败状态,并阻止进一步的输入。

可以使用std::cin.clear()轻松修复它。使用std::string存储输入并让它处理长度也是一种替代方法。

相关:

关于c++ - getline() 和输入流的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67904226/

相关文章:

php - 无权使用 Datastream 错误消息(皇家邮政运输 API)

c++ - 我应该使用什么来代替 std::ostrstream?

c++ - 从 std::cin 读取二进制数据

c++ - 对用户生成的数组进行排序有垃圾数据

c++ - 引用包含对象引用的 STL vector 会在 C++ 中生成错误。为什么?

c++ - 为什么 std::basic_ios 有一个公共(public)构造函数?

c++ - Boost async_read_some 不完全是异步的

c++ - cin.fail while循环输入再入

c++ - 无法将 'TCHAR*' 转换为 'const char*'

c++ - 安卓NDK : gnuSTL_static library documentation?