gpt4 book ai didi

c - 运行时 scanf 函数的垃圾值无法正常工作

转载 作者:行者123 更新时间:2023-11-30 20:34:50 25 4
gpt4 key购买 nike

下面的 C 程序不会抛出错误,但也不工作,并给出垃圾值。请告诉我为什么?

我正在使用Codeblock编辑器。当我在程序中不使用数组时,程序运行良好。但是我已经仔细阅读了它,没有发现任何错误。

#include<stdio.h>

int main(){
char name1[27];
int maths;
int physics;
int Cs;
int bio;
int english;
int urdu;
int ps;
int isl;

printf("What is your name : ");
scanf(" %s",name1);
printf("\n\nwhat is your score in Mathematics : ");
scanf(" %d",&maths);
printf("\n\nwhat is your score in physics : ");
scanf(" %d",&physics);
printf("\n\nwhat is your score in computer science : ");
scanf(" %d",&Cs);
printf("\n\nwhat is your score in biology : ");
scanf(" %d",&bio);
printf("\n\nwhat is your score in English : ");
scanf(" %d",&english);
printf("\n\nwhat is your score in Urdu : ");
scanf(" %d",&urdu);
printf("\n\nwhat is your score in Pakistan study : ");
scanf(" %d",&ps);
printf("\n\nwhat is your score in Islamiat : ");
scanf(" %d",&isl);

printf("\n****************************************************************************************");
printf("\nName Mathematics Physics Com.sc Biology English Urdu Pak-Study Islamiat");
printf("\n****************************************************************************************");
printf("\n%-16s%-15d%-11d%-10d%-11d%-11d%-8d%-13d%0d",name1,maths,physics,Cs,bio,english,urdu,ps,isl);
return (0);
}

最佳答案

如果问题是输入带有空格的姓名,例如姓名和姓氏,您应该使用 fgets检索输入字符串并手动删除换行符

#include<stdio.h>
#include <string.h>

int main(void)
{
char name1[27];
int maths;
int physics;
int Cs;
int bio;
int english;
int urdu;
int ps;
int isl;

printf("What is your name : ");
fgets(name1, sizeof(name1), stdin);
name1[strcspn(name1, "\n")] = 0;

printf("\n\nwhat is your score in Mathematics : ");
scanf(" %d",&maths);
printf("\n\nwhat is your score in physics : ");
scanf(" %d",&physics);
printf("\n\nwhat is your score in computer science : ");
scanf(" %d",&Cs);
printf("\n\nwhat is your score in biology : ");
scanf(" %d",&bio);
printf("\n\nwhat is your score in English : ");
scanf(" %d",&english);
printf("\n\nwhat is your score in Urdu : ");
scanf(" %d",&urdu);
printf("\n\nwhat is your score in Pakistan study : ");
scanf(" %d",&ps);
printf("\n\nwhat is your score in Islamiat : ");
scanf(" %d",&isl);

printf("\n****************************************************************************************");
printf("\nName Mathematics Physics Com.sc Biology English Urdu Pak-Study Islamiat");
printf("\n****************************************************************************************");
printf("\n%-16s%-15d%-11d%-10d%-11d%-11d%-8d%-13d%0d",name1,maths,physics,Cs,bio,english,urdu,ps,isl);
return (0);
}

关于c - 运行时 scanf 函数的垃圾值无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41180360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com