python1010101 February 2016

C: loop on 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);
        }
    }

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?

Answers


chux February 2016

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

Post Status

Asked in February 2016
Viewed 1,398 times
Voted 5
Answered 1 times

Search




Leave an answer