为什么从输入中收集字符串时整数输出为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 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
相关文章:
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 为对象分配整数.输出将是什么?
- 在 c++ 中输出 64 位整数
- Vscode/C++ - cout 无法输出完整的句子,也无法与整数连接
- 为什么输出是整数而不是双精度?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- C++ 读取未知数量的整数到 cin 并输出总和
- libmpg123 在我使用整数编码读取 mp3 时强制浮点输出
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 按升序输出整数时,将最后一个整数放在新行上
- 如何包含整数之间的空格作为输出
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 输出显示多个带整数的字符串值
- 为什么从输入中收集字符串时整数输出为0
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- 输出可序列化的排序整数
- C++随机函数给出的相同整数是输出的两倍
- 整数输出格式.什么是 printf(%.3x) 的类似物
- 为什么固定宽度的整数输出的是字符而不是整型?