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

C中的cin试图将字符串值赋给int变量?

发布时间:2020-12-14 17:52:00 所属栏目:百科 来源:网络整理
导读:我正在研究Bjarne Stroustrup的编程 – 使用C的原理和实践,并得出以下示例: #include "std_lib_facilities.h"int main() { /* Name and Age input */ cout "Please enter your first name and agen"; string first_name = "???"; int age = -1.0; cin firs
我正在研究Bjarne Stroustrup的编程 – 使用C的原理和实践,并得出以下示例:

#include "std_lib_facilities.h"

int main() {
    /* Name and Age input */
    cout << "Please enter your first name and agen";
    string first_name = "???";
    int age = -1.0;
    cin >> first_name >> age;
    cout << "Hello," << first_name << "(age " << (age * 12) << " months)n";
    return 0;
 }

如果你运行程序并输入Carlos 22,它将正确输出Hello,Carlos(22岁).但是,如果你输入22 Carlos,他说输出应该是Hello,22(年龄-1)因为“Carlos不是整数……它不会被读取”.但是,当我运行它时,它会返回Hello,22(0岁),这似乎是在为它分配垃圾值.我很好奇为什么会发生这种情况,因为本书暗示除非你输入一个整数,否则它不会尝试为年龄变量赋值.我使用断点运行代码,并在输入非整数输入后确认年龄值的值从-1变为0.

难道我做错了什么?或者这是一个奇怪的事实,因为我正在通过Xcode和它包含的任何编译器构建它?

解决方法

如果您按照通话中的电话跟踪

cin >> age;

你最终调用了std::strtol. strtol的返回值是:

  • If no conversion can be performed,?0? is returned.

在通话后检查cin的状态,以确保所有提取都成功.

cin >> first_name >> age;
if ( cin )
{
   // Extraction was successful.
   // Use the data.
}
else
{
   // Extraction was not successful.
   // Deal with the error.
}

(编辑:李大同)

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

    推荐文章
      热点阅读