0

Hi I know this will be quite an easy question but i'm quite a beginner yet.

I was practicing on "for"-loops on C and wanted to write a program that asks you to input a number and that recognises whether your input is really a number. in case it isn't a number the program has to reiterate the question until the input is actually a number.

The code i came up with is the following:

#include <stdio.h>

int main () {
  float a;
  int n;
  for(n = 0; n == 0;) {
    printf("Insert your number:\n");
    n = scanf("%f", &a);
  }
  printf("You wrote a number!\n");
}

n is supposed to be the number of conversions the scanf function performed, so when that value is 1 we know the user actually wrote a number and not a character. this code looked fine but when i ran it I found a strange error. if I put a number in it just runs smoothly and straight out tells me i wrote a number. If i try to put a character in, let's say for example the letter 'a', it goes in an infinite loop and just keeps prinitng "Insert your number:" in the terminal endlessly.

it looks like he understands that n is not equal to one so it starrts executing the commands in the for{} function but for some reason it keeps skipping the "scanf" command. thus the n-value never changes and the program keeps running the cicle for ever.

What causes this error? and how do I fix it?

Defcon97
  • 111
  • 3
  • 1
    The code shown will not even enter the body of the loop. Please post your actual code. – too honest for this site Nov 09 '16 at 20:00
  • This is a very wrong code you have given! – skrtbhtngr Nov 09 '16 at 20:03
  • Scanf scans for a number, if if finds one it will remove the corresponding text from stdin. You dont enter a number, so the function fails without removing anything. The next iteration your old input is still waiting. You need to use fgets to take a whole line, then you can parse it with sscanf for example – Norbert Lange Nov 09 '16 at 20:05
  • i don't know why you say the code is wrong really...it compiles without any warning or errors with gcc. @NorbertLange ok i think i get what you are saying but i am not familiar with "fgets" can you mane an example of it should be written? – Defcon97 Nov 09 '16 at 20:23
  • @Defcon97: just because it compiles doesn't mean it's right. You initialize `n` to 0, which causes `n != 0` to evaluate to `false`, so the loop body isn't entered at all. I think you meant to write `n == 0`, which indicates that the `scanf` call didn't match the input. However, if a matching failure occurs, the offending character is left in the input stream to foul up the next read. You'll want to remove it with a `getchar()` call or something like that before trying another `scanf`. – John Bode Nov 09 '16 at 21:10
  • @JohnBode oh sorry yeah you are right that was a typo...my bad i'll edit it right away – Defcon97 Nov 09 '16 at 21:13

0 Answers0