为什么第一个循环打印01然后执行gets()函数? [英] why does the first loop print 01 and then executes gets() function ?

查看:77
本文介绍了为什么第一个循环打印01然后执行gets()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #include< stdio.h> 
#include< string.h>
int main()
{
int 条目,i,选项;
printf( \ n请指出您要输入的记录数:\ n);
scanf( %d,& entry);
char ent [entry] [ 100 ],name [entry] [ 20 ],姓[entry] [ 20 ],得分[entry] [ 10 ];
printf( \ n请输入学生的记录(在每条记录后输入一个新行),如下格式名字姓氏得分\ n);

for (i = 0 ; i< entry-1; i ++)
{
printf( %d,i);
得到(ent [i]);
printf( %s,ent [i]);
}

for (i = 0 ; i< entry -1; i ++)
{
strncpy(name [i],strtok(ent [i], ), sizeof (name [i]));
printf( \ n%s \ n,name [i]) ;
}

printf( \ n请选择合适的选项:< /跨度>);
printf( \ n打印记录(按1)\ n按名字搜索(按2) \\ n按姓氏搜索(按3)\ n按分数排序(按4)\ n按姓氏排序(按5)\ n退出程序(按0)\ n);
scanf( %d,& option);
return 0 ;
}

解决方案

基本上因为获取获取(原谅双关语) ) scanf 未完成缓冲区。您可以很容易地看到更改为

Quote:

printf(%d,i);

得到(ent [i]);

printf(%s,ent [i]);





 printf( %d \ n ,一世); 
得到(ent [i]);
printf( [%s] \ n,ent [i]);


#include<stdio.h>
#include<string.h>
int main()
{
    int entry,i,option;
    printf("\nPlease indicate the number of records you want to enter :\n");
    scanf("%d",&entry);
    char ent[entry][100],name[entry][20],surname[entry][20],score[entry][10];
    printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n");

    for(i=0;i<entry-1;i++)
    {
        printf("%d",i);
        gets(ent[i]);
        printf("%s",ent[i]);
    }

    for(i=0;i<entry-1;i++)
    {
        strncpy(name[i],strtok(ent[i]," "),sizeof(name[i]));
        printf("\n%s\n",name[i]);
    }

    printf("\nPlease choose the appropriate options :");
    printf("\nPrint records (press 1)\nSearch by first name (press 2)\nSearch by last name (press 3)\nSort by score (press 4)\nSort by last name (press 5)\nExit the program (press 0)\n");
    scanf("%d",&option);
    return 0;
}

解决方案

Basically because gets gets (pardon the pun) scanf unconsummated buffer. You may easily see that changing from

Quote:

printf("%d",i);
gets(ent[i]);
printf("%s",ent[i]);


to

printf("%d\n",i);
gets(ent[i]);
printf("[%s]\n",ent[i]);


这篇关于为什么第一个循环打印01然后执行gets()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆