C: loop on scanf

2019-05-24 10:37发布

问题:

    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);
        }
    }

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.

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?

回答1:

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