0
Input validation in C
Here's my code, can someone tell me how to break the while loop outside when all characters are digits except the last character enter is pressed? And can someone please teach me how to create a function solely for validation based on my codes below? Thanks! void validation() { char inputs[50]; int a = 0, result = 0; while(a == 0) { printf("Enter smth = "); fgets(inputs, 50, stdin); for (int i = 0; i < 10; i++) { if (inputs[i] == '\0' || inputs[i] == '\n') { break; } if (!isdigit(inputs[i])) { printf("Invalid inputs!\n"); break; } if (strlen(inputs) > 10) { printf("Invalid range!\n"); break; } } } }
3 Antworten
+ 4
It's simple asuna ;)
break statements inside the if blocks terminate the inner for loop when the first invalid character is encountered. Then, the program flow jumps one scope up and reaches to the while loop outer block which in this case acts like an infinite loop -- since 'a' doesn't get altered nowhere inside the body of the while, a == 1 is always true. So, changing the value of the 'a' is the only possible scenario to alter the while loop condition for terminating the program execution without applying radical changes to the program structure.
+ 4
Did you try to change the value of 'a' inside the if blocks before break, for example, like
if (!isdigit(input[i])) {
//...
a = 1;
break;
}
0
No.. Can you briefly explain why need to change the value of 'a'?