为什么从输入中收集字符串时整数输出为0
Why is integer output 0 when collecting string from input
我是 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++ 的新手,正在学习 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