You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++作业程序输出异常:姓名显示不全且年龄计算错误求助

问题修复方案

错误原因

  1. 你定义的char name;只能存储单个字符,输入"Nate"时只会读取第一个字母'N',剩余内容留在输入缓冲区中。
  2. 后续读取出生年份时,缓冲区里的内容不是数字,导致birth变量未被正确赋值,最终年龄计算结果出错。

快速修复步骤

  • 将存储姓名的变量类型从char改为string,这样就能完整存储姓名字符串。
  • 由于使用string需要对应的头文件支持,在#include<iostream>下方添加#include<string>。

修复后的完整代码

// Nate Banks
// Homework 2
// 10/25/2022

#include<iostream>
#include<string> // 新增头文件,用于支持string类型
using namespace std;

int main()
{
    string name; // 改为string类型存储姓名
    int birth;
    int year = 2022;

    cout << "Please enter your name and year of birth:";
    cin >> name >> birth;

    cout << "Hi " << name << "!" << " You are " << year - birth << " years old!";

    return 0;
}

修改后输入"Nate 2003",就能得到正确输出:Hi Nate! You are 19 years old!

内容的提问来源于stack exchange,提问作者Nate Banks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:00:56