【发布时间】:2014-03-24 02:38:48
【问题描述】:
我正在尝试读取包含空格的字符串,因此 scanf 无法正常工作,因此我正在尝试使用 fgets。当我运行它并点击 if 语句时,屏幕上打印的是:
Please enter the course name.
You entered the course:
Please enter the course ID.
=========================
if(coursetotal==0)/*start of 1 course*/
{
printf("Please enter the course name.\n");
fgets(course[0].name,sizeof(course[0].name),stdin);
printf("You entered the course name: %s\n",course[0].name);
printf("\nPlease enter the four digit course ID.\n");
int temp=0,temp1=0,count=0; /*Variables used to check if 4 digits*/
scanf("%d",&temp);
temp1=temp;
while(temp1!=0)
{
temp1/=10;
count++;
}
if(count==4)/*start of is 4 digits*/
{
course[0].id=temp;
coursetotal+=1;
printf("You entered the course ID: %d\n",course[0].id);
}/*end of is 4 digits*/
else
{
printf("The course ID you input was not 4 digits.\n");
return;
}
printf("You have successfully added the course: %s. The ID is : %d, and you now have a total of %d course.\n",course[0].name,course[0].id,coursetotal);
} /*end 1 course*/
【问题讨论】:
-
因为在开始时 sizeof(course[0].name) 为 0,所以它不占用任何字符............从以下位置读取 fgets() 函数tutorialspoint.com/c_standard_library/c_function_fgets.htm
-
您可能在之前的用户交互中在输入队列中留下了换行符。尝试在
fgets之前调用getchar作为测试。真正的解决方案取决于您如何处理之前的交易。 -
@JatinKhurana
sizeof()怎么可能返回零? -
不如先检查一下你的 api 函数结果。 C 编程的The Sixth Commandment 从小就应该认真对待,初学者代码中最常见的错误常常归因于天真的假设,即如果某些东西通常有效,它就会永远有效。
-
避免将
scanf()与fgets()混合使用。正如@user3386109 所说,您有来自scanf()等的剩余\n。使用fgets()和sscanf()或strtol()读取整数。