Note that there are some explanatory texts on larger screens.

plurals
  1. POInfinite loop scanf-function
    text
    copied!<p>I am learning c and understand that this language is low-level and in this context lacks exception handling. </p> <p>I made a simple program where the user choose among some alternatives from a menu. Its just that simple!</p> <p>The program is divided into a few methods - one of the methods waits for the user to press a key - an integer is expected. Then return this integer to another method which holds a switch-structure. </p> <p>The problem arises when a character is pressed - in most cases an infinite loop of the else-block is started. </p> <p><em>You must choose an alternative 0 - 2. Please try again :-)</em></p> <p><em>You must choose an alternative 0 - 2. Please try again :-)</em></p> <p><em>You must choose an alternative 0 - 2. Please try again :-)</em></p> <p>...... and so on</p> <p>I do not actually know how to solve this. I have tried to use the return value from the scanf-function without success. I have also tried to pass a character (instead of integer) as an argument to the scanf-function - also without success.</p> <p>Any suggestion how to handle this problem? </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void menu(); void runSelection(int selection); int getSelection(); int pause(); int main(void) { do{ menu(); runSelection(getSelection()); }while(pause()); return 0; } int pause() { int c; printf("\n\nPress enter to continue!"); fflush(stdout); /* flush inputstream */ while((c = getchar()) != '\n' &amp;&amp; c != EOF); getchar(); return 1; } void menu() { puts(" * * * * * * M E N U * * * * * * *"); puts("1. Do something 1"); puts("2. Do something 2"); puts("3. Do something 3"); fflush(stdout); } void runSelection(int selection) { switch (selection) { case 0: puts("you pressed 0"); break; case 1: puts("you pressed 1"); break; case 2: puts("you pressed 2"); break; } } int getSelection() { int key; int true = 0; do { scanf("%d", &amp;key); if (key &gt;= 0 &amp;&amp; key &lt;=2) { true = 1; } else { puts("You must choose an alternative 0 - 2. Please try again :-)"); fflush(stdout); } } while (true == 0); return key; } </code></pre>
 

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