0

I have recently been trying to do an exercise in c.

I want to read the input which is something like: "SET 0" (note that the actual text will be parsed later).

I tried fgets as it is like that:

char in[20];
//ok, this reads the first line, the first input is meant to be a number
scanf("%s",in);

if(isdigit(in[0])){

    char array[]={'?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?'};

    auto counter = atoi(in);

    while(counter !=0){

        fgets(in, sizeof(in),stdin);

For some reason, when i type eg "SET 0" and i am using fgets the in variable is empty(will print nothing).

I tried scanf but it will not read the number.

Any ideas/suggestions of what i can do?

Thanks in advance!

  • `auto counter = atoi(in);` It's funny how it just works here, but I believe `auto` doesn't mean what you think it does. `what i can do?` What do you want to do? What should the result be? I don't understand, what exactly have you tried? How did you check if `in` variable is empty after using `fgets`? How did you use `fgets`? Did you check `fgets` return value? – KamilCuk Jan 15 '20 at 01:40
  • If the input is 'SET 0', then scanf will set `in` to the string "SET". So `isdigit(in[0])` is false. – William Pursell Jan 15 '20 at 02:11
  • Konstantinosm Are you using a [C++ compiler](https://en.cppreference.com/w/cpp/language/auto)? – chux - Reinstate Monica Jan 15 '20 at 02:48
  • Never do `scanf("%s", ...)`. It is unsafe and probably doesn't do what you expect it to do. – HAL9000 Jan 15 '20 at 03:58

1 Answers1

0

Do not mix fgets() with scanf() until you know why scanf()` is evil.

fgets() read the left over '\n' of the first line of user input which scanf() did not read.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256