c++ - 空输入对 cin.get() 意味着什么?

标签 c++ input cin

我觉得是个简单的问题,但是我不明白这个代码示例中的概念,主要是在while循环中:

#include <iostream>

const int ArSize = 10;
void strcount(const char * str);

int main(){
    using namespace std;
    char input[ArSize];
    char next;


    cout << "Enter text:\n";
    cin.get(input, ArSize);
    while(cin){

        cin.get(next);
        while(next != '\n')
            cin.get(next)
        
        strcount(input);
        cout << "Enter next line, empty line ends the program:\n";
        cin.get(input, ArSize);
    }

    cout << "The end\n";
    return 0;
}

...

我的理解是 while 循环一直持续到 cin 返回 false。它过滤掉缓冲区中剩余的输入(因为它不是 ArSize 或以下的大小,或者它是 - 然后它只会过滤掉换行符)直到它遇到换行符。然后它计算字符串的字符(在这个问题中不重要),然后,假设有人只是按回车键。 cin.get() 丢弃输入中的换行符。因此,例如,如果某人在终端中输入了一个空文本行,它会将其读取为“失败”输入并且 cin 返回 false?因为如果有人继续换行,只需按回车键,它只会将换行符留在缓冲区中,而 cin.get() 无法获取它,因此它会返回 false。还是我错了?

简而言之 - 如果您直接按回车键,究竟会发生什么? cin.get() 无法获取输入,因为缓冲区中只有换行符并将其视为失败输入,因此返回 false?

最佳答案

如果cin.get(input, ArSize);不读取任何字符(即它遇到的第一个字符是换行符)它调用 setstate(failbit) 将流置于失败状态,因此 while(cin) 变为 false,结束循环。

关于c++ - 空输入对 cin.get() 意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70618350/

相关文章:

c++ - Boost::序列化 std::unordered_map<double, std::vector<double>>

php - 为什么我的表单变量没有通过 POST 传递?

shell - 我们如何通过使用 isatty 函数来区分我们程序的输入是定向的还是只是用户的输入?

c++ - 刷新 cin 输入的正确方法

c++ - 使用 istream (std cin) : prevent "[input] is not recognized as ..." on Windows

c++ - 使用 cout 从 cin.get() 输出类型 int

c++ std::copy 类型转换为派生类可能吗?

c++ - PCL 和 CMake : StatisticalOutlierRemoval undefined while linking 问题

c++ - 如何创建 makefile 构建 Snappy 作为静态库

iphone - iOS 7 Safari : OS locks up for 4 seconds when clicking/focusing on a HTML input