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

前端之家收集整理的这篇文章主要介绍了C中的cin试图将字符串值赋给int变量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在研究Bjarne Stroustrup的编程 – 使用C的原理和实践,并得出以下示例:

#include "std_lib_facilities.h"

int main() {
    /* Name and Age input */
    cout << "Please enter your first name and age\n";
    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.
}

猜你在找的Xcode相关文章