当我们使用 std::cin 将“char 类型”值存储在“整数类型”变量中时会发生什么?

问题描述 投票:0回答:2
int i;
std::cin >> i; // i = 'a'

当我们尝试这样做时,

std::cin
有什么反应?
我们知道,当
std::cin
获取一个值时,它会将其转换为 ASCII 或其他内容,然后将其存储在变量中,那么
std::cin
对此有何反应?

c++ stream cin
2个回答
3
投票

不,它不存储您输入的字符的 ASCII 值

i
。相反,该流将为输入流放置一个失败标志,这意味着整数的读取导致失败。这是演示这一点的代码。

int i;
cout << cin.fail();     // 0 as cin doesn't failed yet
cin >> i;               // A char is entered instead of integer
cout << cin.fail();     // 1 as cin failed to read a character  

3
投票

如果您正在读取的值符合您的预期,则应该对

std::cin
进行错误检查,否则
std::cin
将失败并且
i
的值将设置为
0

#include <iostream>

int main()
{
    int i;
    if(std::cin >> i)
    {
        std::cout << i << std::endl;
    }
    else 
    {
        std::cin.clear();
        std::cout << "No integer" << std::endl;
    }

    return 0;
}

您还可以使用

while
循环来处理错误检测。一个例子如下:

#include <iostream>
#include <limits>


int main()
{
    int age { };

    // executes the loop if the input fails or is out of range (e.g., no
    // characters were read)
    while ( ( std::cout << "How old are you? " ) &&
            ( !( std::cin >> age ) || age < 1 || age > 200 ) )
    {
        std::cout << "That's not a number between 1 and 200; ";
        // clear bad input flag
        std::cin.clear();
        // discard bad input
        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    }

    std::cout << "You are " << age << " years old.\n";
}

输入/输出示例:

How old are you? a
That's not a number between 1 and 200; How old are you? #12gj
That's not a number between 1 and 200; How old are you? foo
That's not a number between 1 and 200; How old are you? 84
You are 84 years old.
© www.soinside.com 2019 - 2024. All rights reserved.