Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy this example is stuck in an infinite loop in C?
    primarykey
    data
    text
    <p>In the example below, if I enter a character in Mac OS X terminal, the program will get stuck in an infinite loop, printing <code>Please enter a number:</code> line after line and never allowing the user to input anything. What's wrong with this code? What is the fix? I want to change the code in a way that if a number is not entered, the user is prompted with an error message and asked to enter a number again. </p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, const char * argv[]) { int number = 0, isnumber; getagin: printf("Please enter a number:\n"); isnumber = scanf("%i", &amp;number); if(isnumber) { printf("You enterd a number and it was %i\n", number); } else { printf("You did not eneter a number.\n"); goto getagin; } return 0; } </code></pre> <p>Edit: I edited the code after reading the suggestions, and fixed the infinite loop problem. This is not a bad fix for the infinite loop problem, and with a simple for loop I tell C to search for any none numeric character. The code below won't allow inputs like <code>123abc</code>.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #include &lt;string.h&gt; int main(int argc, const char * argv[]) { char line[10]; int loop, arrayLength, number, nan; arrayLength = sizeof(line) / sizeof(char); do { nan = 0; printf("Please enter a number:\n"); fgets(line, arrayLength, stdin); for(loop = 0; loop &lt; arrayLength; loop++) { // search for any none numeric charcter inisde the line array if(line[loop] == '\n') { // stop the search if there is a carrage return break; } if((line[0] == '-' || line[0] == '+') &amp;&amp; loop == 0) { continue; } // Exculude the sign charcters infront of numbers so the program can accept both negative and positive numbers if(!isdigit(line[loop])) { // if there is a none numeric character then add one to nan and break the loop nan++; break; } } } while(nan || strlen(line) == 1); // check if there is any NaN or the user has just hit enter sscanf(line, "%d", &amp;number); printf("You enterd number %d\n", number); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload