C: 在 scanf 上循环 [英] C: loop on scanf

查看:41
本文介绍了C: 在 scanf 上循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    char buf[1024] = {0};

    // send a message
    if(status == 0) {
        while(1) {
            printf("Enter message : ");
            scanf("%1023[^\n]", buf);
            fflush(stdin);
            if(strcmp(buf,"quit")==0)
                break;
            status = write(s, buf, strlen(buf));
            fflush(stdout);
            memset(buf,0,sizeof buf);
        }
    }

对于我的 scanf,我想加入空格.但是,如果我运行这部分代码,输入消息:"将处于无限循环中.

For my scanf, I want to take in spaces. However if I run this part of the code, the "Enter message: " will be in an infinite loop.

如果我仅将 scanf 更改为 "%s" 则它可以正常工作,但我无法接受中间有空格的输入.

If I change scanf to "%s" only then it works normally but i cannot take in inputs with space in between.

任何人都可以帮助发现它是如何引发无限循环或解决此问题的任何想法吗?

Could anyone help in spotting how come it is throwing infinite loop or any ideas to fix this?

推荐答案

scanf() 在阅读时出错的方法太多了.使用 fgets()

scanf() simply has too many ways to go wrong reading a line. Use fgets()

char buf[1024] = {0};

// send a message
if(status == 0) {
    while(1) {
        printf("Enter message : ");
        if (fgets(buf, sizeof buf, stdin) == NULL) break;
        //scanf("%1023[^\n]", buf);
        //fflush(stdin);

        buf[strcspn(buf, "\n")] = '\0'; // lop off potential \n

        if(strcmp(buf,"quit")==0)
            break;


        status = write(s, buf, strlen(buf));
        // fflush(stdout);
        memset(buf,0,sizeof buf);
    }
}

这篇关于C: 在 scanf 上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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