Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux, scanf in loop, while stdin already loaded

Tags:

c

linux

I have trouble with scanf and a loop on linux.

#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>

int main(int argc, char ** argv){
    int i = 0;
    char s[255];
    char c;

    while(i<10){
        printf("Here : ");
        scanf(" %s", s);
        printf("%s\n", s);
        i++;
        while((c = getchar()) != '\n' && c != EOF);
    }

    return EXIT_SUCCESS;
}

If in the shell Linux, if I execute my file like this :

echo "lol" | ./testWhileScanf

Then the result will be this :

Here : lol

Here : lol

Here : lol

Here : lol

Here : lol

Here : lol

Here : lol

Here : lol

Here : lol

Here : lol

I dont know why this is the result, a line of my code is to flush the stdin, to not have this kind of problem.

Seeking for solution I tried : __fpurge, fpurge, fflush But none worked.

I would like to get only :

Here ? : lol

Here ? :

And waiting for input. Surely I am missing something here.. but I can't figure what =/

like image 215
KlossOne Avatar asked Apr 06 '26 06:04

KlossOne


1 Answers

When you call

scanf(" %s", s);

for the first time, it sets s to lol, and returns 1. When you call it for the second time, there is no further input, so scanf returns zero without setting your variable. However, your code ignores the return value of scanf, and prints s anyway.

Adding a check and a break should fix this problem:

if (scanf(" %254s", s) != 1) break;

Note the size limiter in the format string, it will prevent scanf from causing buffer overruns.

like image 89
Sergey Kalinichenko Avatar answered Apr 09 '26 00:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!