c++ - 在代码中使用 cin.get() 双倍输出

标签 c++

所以我正在自学 C++,我看不出这里有什么问题:

代码:

// Arrays.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0;
    char input = ' ';

    for(i = 1; i <= 100; ++i)
    {
        std::cout << "enter a value for element number " << i << ": " ;
        do
        {
            input = std::cin.get();
            std::cout << "recorded element in position " << i << " is " << input << "\n"; 
        } while (!input == 'q') ;
    }
}

问题:

第 17 行:输入 std::cin.get();

它给我这个:它要求输入,然后记录它并自动为我完成元素 2

enter a value for element number 1: 5 recorded element in position 1
is 5 enter a value for element number 2: recorded element in position
2 is

enter a value for element number 3:

但是当我用 std::cin >> input 替换它时,它没有,为什么?

最佳答案

您似乎输入了一个换行符:当您使用回车键时,您会得到另一个字符 ( '\n' ),它也是从 std::cin.get() 获得的.成员(member)std::istream::get()是一个未格式化的输入函数,如果尝试读取,它不会在尝试读取任何内容之前尝试跳过空格。

另一方面,当使用格式化输入时,例如 std::cin >> input在尝试读取内容之前,流将跳过所有前导空格。也就是说,您也输入的换行符将被跳过。

您可以使用 (std::cin >> std::ws).get()在使用 get() 之前消耗前导空格. ...反之亦然,您可以使用 std::cin >> std::noskipws 为格式化输入设置流而不自动跳过前导空格(并使用 std::cin >> std::skipws 再次反转此设置)。不过,一般来说,不建议不要跳过格式化输入的前导空格。

关于c++ - 在代码中使用 cin.get() 双倍输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21081048/

相关文章:

c++ - 专用结构/类中未识别的数据成员

c++ - 我怎样才能编辑这一行不再是一个警告

c++ - sleep 功能不起作用

c++ - STL 列表 - 如何通过其对象字段查找列表元素

C++ VS2010 判断是 Release 还是 Debug

c++ - 在 C++ 中使用字符串数组

c++ - Qt 5.1 应用程序无法在 QtCreator 之外的 Windows 8 上运行,运行时错误

c++ - 如何将托管数组传递给函数?

c++ - 模拟数据包发送和接收

c++ - 构造函数返回值