欣坚强 2022-01-13 15:46 采纳率: 57.4%
浏览 11
已结题

为什么当输出结果时,student2.score前面会有多余的换行

代码

#include<iostream>

using namespace std;

int main()
{
    struct Student 
    {
        int num;
        char name[20];
        double score;
    }student1,student2;
    
    cin>>student1.num>>student1.score;
    fgets(student1.name,20,stdin);
    
    cin>>student2.num>>student2.score;
    fgets(student2.name,20,stdin);
    
    if(student1.score>student2.score) cout<<student1.num<<student1.name<<student1.score<<endl;
    else  cout<<student2.num<<student2.name<<student2.score<<endl;
    
    return 0;
}

输入
10101 89 wang
10103 90 lin
输出结果
10103 lin
90

  • 写回答

1条回答 默认 最新

  • Dana_ranmo 2022-01-13 16:26
    关注

    “但是需要注意的是,如果输入的字符串长度没有超过 n–1,那么系统会将最后输入的换行符 '\n' 保存进来,保存的位置是紧跟输入的字符,然后剩余的空间都用 '\0' 填充。所以此时输出该字符串时 printf 中就不需要加换行符 '\n' 了,因为字符串中已经有了。”------------from c.biancheng.net/view/235.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 1月13日
  • 已采纳回答 1月13日
  • 创建了问题 1月13日

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C