C While Loop not working like C++

Hi new to C give me a hand thank.

do
{
          bzero(input,256);
          printf("Please enter the country name!"); 
          scanf("%[^\n]s",input); //& character is essential for scanf(), %f = float, %399s as the last character to be the null character ('\0').  
}
while (strcmp(end,input) != 0);//Compare two strings

It work it can loop but it will skip the scanf when it go into loop. Thank ppl

It's not a C thing, it's a scanf thing. scanf leaves the character it stops at in the buffer so next loop, it fails instantly!

Don't use scanf to read lines, that's overkill anyway -- use the purpose-built line reading function: fgets. fgets(buf, size, handle); Be warned that it leaves in the ending newline.

If you need to parse values from individual lines in a scanf-like manner, read lines with fgets() and parse them with sscanf(buffer, "command", &val); Does the same thing without the buffer problems.

You should also be checking fgets' return value to see if you hit EOF before you hit the ending word, otherwise your code might end up in an infinite loop.

It's unnecessary to bzero your buffer every time. Nearly all stdio functions add the null terminator for you. Exceptions include strncpy and memcpy.

1 Like

Hi ALL!!
I solve my own qn...

scanf("%[^\n]s",input);

put a space before the % and the loop will go in to scanf =) hope it help people in further need

That's because the space will accept any whitespace, including \n.

It's still overkill to use scanf for individual lines. I suggest you read my above post.

fget() have buffer problem like u say... it take in my whole buffer.. i dont understand your solution can give an example?? btw why say using scanf is overkill... i totally noob in C thank for your time =) really look forward to your ans

scanf is overkill for reading lines one by one, because it's a pretty complicated text processing function which would have some overhead. It also has unwanted side-effects, as you discovered. fgets() is a purpose-built function that reads individual lines.

char buf[512];

// read lines one by one
while(fgets(buf, 512, fp) != NULL)
{
        int a,b,c;

        // Break the loop on the line END
        if(strcmp(buf, "END\n") == 0) break;

        // Ignore lines that aren't three numbers separated by spaces
        if(sscanf(buf, "%d %d %d", &a, &b, &c) != 3)
                continue;

       printf("scanf read %d %d %d\n", a, b, c);
}

Since sscanf isn't reading from your file, it can't leave junk in the buffer to foul you up later.