Reputation: 5
I'm new to C and I've checked for some solutions, though I can only find stuff for chars (and tried their solutions with chars), it didn't work aswell, I want to know why I'm infinitely looping (Can't input anything aswell). What I expect is a new input when I enter for example a letter.
#include <stdio.h>
#pragma warning(disable:4996)
int main(void)
{
float num1;
while (!(scanf("%f", &num1)))
{
scanf("%f", &num1);
}
}
Upvotes: 0
Views: 82
Reputation: 678
#include <stdio.h>
float get_float_input() {
// Not portable
float num1;
while (!(scanf("%f", &num1))) {
fseek(stdin, 0,
SEEK_END); // to move the file pointer to the end of the buffer
}
return num1;
}
float get_float_input_func() {
// Portable way
float num1;
int ch;
char buff[1024];
while (1) {
if (fgets(buff, sizeof(buff), stdin) == NULL) {
while ((ch = getchar()) != '\n' && ch != EOF)
; // Clearing the input buffer
continue;
}
if (sscanf(buff, "%f", &num1) != 1) {
continue;
}
break;
}
return num1;
}
int main(void) {
float num1;
num1 = get_float_input_func();
printf("%f\n", num1);
return 0;
}
Upvotes: 1