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

标签 c++ std stdin cin stdstring

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

#include <iostream>
#include <string>

int main() {
  std::cout << "Please enter your first name and age\n";
  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;

我希望输出为“Hello, 22 (age -1)”,如文本中所述,但得到的却是“Hello, 22 (age 0)”。为什么?

最佳答案

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

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until C++11)

If extraction fails, zero is written to value and failbit is set. (since C++11)

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

关于c++ - 为什么从输入收集字符串时整数输出为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51453994/

相关文章:

c++ - 改变QLabel文本的颜色?访问和修改.ui 文件的成员? [Qt]

android - 如何在 C/C++ 中方便地发布算术溢出异常

c++ - 尽管索引远低于容量,vector.at() 仍然阻塞

c++ - 高效的中值计算

ruby - 将 Hex STDIN/ARGV/gets 转换为 ruby​​ 中的 ASCII

java - bash 和 Java 之间的标准输入切换

c++ - C++ 窗口的简单 Microsoft 示例无法编译

C++0x : rvalue reference versus non-const lvalue

c++ - 使用 const_iterator 时的断言

用于标准输入测试的 Golang 模式