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?