我是 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/