c语言中字符数组输出乱码

int addbook(){    system(CLEAR);      ///////////////////////////////////////////    char sname[MAXNAME];    char author[MAXNAME]={0};    char publisher[MAXNAME]={0};    int id, count;    char *namep;    while(1)        {        id = 0;        count = 0;        namep = NULL;        printf("请输入图书名:\n");        scanf("%s", sname);        getchar();        printf("请输入图书的作者:\n");        scanf("%s", author);        getchar();        printf("请输入图书的出版社:\n");        scanf("%s", publisher);        getchar();        printf("请输入小于10000的图书编号:\n");        scanf("%d", &id);        getchar();        if(!(id > 0 && id < 10000))        {            error("输入编号不符合要求");            fflush(stdin);            continue;        }        printf("请输入小于500的图书数量:\n");        scanf("%d", &count);        getchar();        if(!(count > 0 && count < 500))        {            error("输入数目不符合要求");            fflush(stdin);            continue;        }        Book *bp;        if((bp = lookup(namep = strdup(sname), id)) == NULL)        {            bp = (Book *)malloc(sizeof (Book));            if(bp == NULL || (bp->name = namep) == NULL)            {                error("注册图书失败");                fflush(stdin);                continue;            }            bp->id = id;            bp->count = count;            bp->author= author;            bp->publisher= publisher;            bp->status = AVAILABLE;            ++nbook;            bp->next = head;            head = bp;            printf("图书 %s 注册成功\n", sname);            return id;        }        else            {            fflush(stdin);            error("图书名或编号已经被占用");        }    } FILE *fp=fopen("file.txt","r+");    if(NULL==fp)    {        printf ("Failed to open the file !\n");        exit (0);    }    fprintf(fp,"%s\t%s\t%s\t%d\t%d\n",sname,author,publisher,count,id);    fclose(fp);    return -1;}

1.将

scanf("%s", sname);        
getchar();  

改为:gets(sname);

其它需要输入字符串的地方都改成这种形式,scanf在碰到空格后就结束,所以在输入书名时,如果有空格,后面的就会乱码。gets函数能够接收空格,按回车时接收终端输入的所有字符。

2.如果按1修改后,仍然无法解决问题,那么,在while循环中,在调用gets函数前,先将缓存重置一下:

memset(sname,0,MAXNAME)

memset函数需要包含<string.h>头文件

如有帮助,请采纳一下,谢谢。

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

把代码规范一下,通过代码段插入代码。