为什么从输入中收集字符串时整数输出为0

Why is integer output 0 when collecting string from input

本文关键字:整数 输出 字符串 输入 为什么      更新时间:2023-10-16

我是C++的新手,正在学习Stroustrup的编程原理和实践。在第3.3节中,他给出了以下示例:

#include <iostream>
#include <string>
int main() {
std::cout << "Please enter your first name and agen";
std::string firstName;
int age;
std::cin >> firstName >> age;
std::cout << "Hello, " << firstName << " (age " << age << ")n";
}

根据文本,我输入了"22 Carlos",并期望输出是22,后面跟着一些随机数或0。好吧,我得了0。

然后我初始化变量并输入相同的"22 Carlos":

string firstName = "???";
int age = -1;

正如文本中所述,我希望输出为"你好,22岁(年龄-1(",但实际输出为"Hello,22(年龄0("。为什么?

age设置为0的原因是(假设您使用的是c++11或更高版本(:

如果提取失败(例如,如果在数字所在的位置输入了一个字母预期(,值保持不变并且设置故障位。(直到C++11(

如果提取失败,则将0写入值并设置故障位。(自C++11起(

顺便说一句,VC++编译器直到最近才遵循这个标准https://developercommunity.visualstudio.com/content/problem/285201/the-value-is-not-zeroed-after-failure-but-it-shoul.html