当我们使用 std::cin 将"char type"值存储在 "integer type" 变量中时会发生什么?


int i;
std::cin >> i; // i = 'a'

当我们尝试这样做时,std::cin的反应是什么
正如我们所知,当std::cin获得一个值时,它会将其转换为ASCII或其他格式,然后将其存储在一个变量中,那么std::cin对此有什么反应?

否,它不存储要输入到i中的字符的ASCII值。相反,流将为输入流放置一个失败标志,这意味着读取整数会导致失败。以下是演示这一点的代码。

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  

如果您正在读取的值如您所期望的那样,则应该对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.

最新更新