加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C cin读取字符串到int类型返回0

发布时间:2020-12-16 10:13:57 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why does stringstream change value of target on failure?????????????????????????????????????2个 #include iostreamusing namespace std;int main(){ cout "Please enter your name and agen"; string first_name; int age; cin first_na
参见英文答案 > Why does stringstream >> change value of target on failure?????????????????????????????????????2个

#include <iostream>
using namespace std;
int main()
{
    cout << "Please enter your name and agen";
    string first_name;
    int age;
    cin >> first_name;
    cin >> age;
    cout << "Hello," << first_name << " (age " << age << ")!n";
}

如果我输入卡洛斯的年龄或任何其他字符串我得到0.这是如何工作(为什么)?

解决方法

不知道为什么这个问题得到了落实/关闭,因为它已经明确说明而且不广泛(从评论来看,很多人都不知道答案)……

无论如何,对于代码:

int age;
cin >> age;

如果输入流不包含任何数字,则将流置于失败状态,将age设置为0.输入流中的字符保留在那里;清除故障状态后,可以通过将来的读操作读取它们.

操作符的行为>>是summarized on cppreference,标准中的完整描述有点复杂.

注意:这在C 11中有所改变;报告垃圾输出的评论员要么是在C 11前模式下运行编译器,要么是有bug的编译器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读