-7

The concept if very simple. The computer must repeat the question till it recieves a valid response. Here is my current code:

#include <stdio.h>


int main(int argc, const char * argv[]) {
int age;

do{
printf("How old are you?\n");
scanf("%d", &age);


if (age == 32767)

{
    printf("Error, retry: \n");
}

else
{
    printf("Cool.");
    break;

}
}
while(age!=3267);

return (0);
}

The if else statement is to catch the exception incase the user types something that is not an integer.

I tried using a do-while loop but it ended up as an infinite loop I used the do-while loop because I needed to go through that procedure until I get a valid age value.

My output with the current code is:

How old are you?
g
Error, retry: 
How old are you?
Error, retry: 
How old are you?
Error, retry: 
How old are you?
Error, retry: 

It goes like this indefinitely.

It would be great if you could help me out.

tryKuldeepTanwar
  • 3,490
  • 2
  • 19
  • 49

3 Answers3

1
  • The computer must repeat the question till it recieves a valid response.
  • It (output) goes like this indefinitely.

Reason :

  • The problem is that you are receiving input only once in your code and then entering into loop to check for the age.
  • since age value is not re-assigned after every iteration, if the first intput is !=32767 it's always wrong and enters into an infinite loop or also known as the odd loop.

    scanf("%d", &age); //scans only once
    
    do //enters loop
    {
        if (age == 32767)
        {
            printf("Error, retry: \n");
        }
    
        else
        {
            printf("Cool.");
        }
    } while(age!=32767);
    

The if else statement is to catch the exception incase the user types something that is not an integer.

  • No, if (age == 32767) would only check if the entered response was equal to 32767 or not.

  • From @davmac 's comment , you can never check for an input value greater than the maximum value of the int variable.

  • Instead it'd be better if you would assign a range this way

     `if (age > 100 || age <0 )`
    

Solution :

to avoid this scan age for every iteration and also see the changes I've done :

do{

    printf("How old are you?\n");

    if(scanf("%d", &age)==1) //checking if scanf is successful or not
    {

        if (age > 100 || age <0 )
        {
            printf("Error, retry: \n");
        }

        else
        {
            printf("Cool.");
            break; //break loop when correct value is entered
        }
    }

    else //if scanf is unsuccessful 
    {
        char c;
        printf("enter only integers\n");

        do
        {
            scanf("%c",&c);
        }while( c !='\n' && c!= EOF ); //consuming characters
    }

}while(1); //always true
Community
  • 1
  • 1
Cherubim
  • 5,287
  • 3
  • 20
  • 37
  • 1
    How can `age > max_value_of_int` ever be true? Also why not use `INT_MAX` rather than trying to guess the maximum value? Finally, what if the `scanf` fails (because input is not a number) - and `age` is left in an uninitialised state? Comparing it then invokes undefined behaviour. – davmac Jul 16 '16 at 09:30
  • @davmac yes yes! forgot about the int overflow :(, i 'll edit in a while – Cherubim Jul 16 '16 at 09:33
  • This is a good answer however the final solution is an infinite loop – Syed Arafat Qureshi Jul 16 '16 at 09:36
  • 1
    Oh my gosh! This is amazing! Thank you!! Can you explain to me how the second else statement works? What does E0F mean? – Syed Arafat Qureshi Jul 16 '16 at 10:19
  • @davmac i've made changes : I avoided checking for max value of int and also checked for the return value of `scanf()`.. thanks for pointing out :) – Cherubim Jul 16 '16 at 10:23
  • @SyedArafatQureshi the second else statement is entered when you `scanf()` is unsuccessful i.e, when a wrong input is given... so in the second else statement using a `while` loop and a character `c`, I scan in all the data in input stream and make it empty for new entry... EOF stands for end of file.. it's useful while taking input from a file :) – Cherubim Jul 16 '16 at 10:28
  • what's the point making a simple thing more and more complex? – tryKuldeepTanwar Jul 16 '16 at 10:28
  • 1
    @Kuldeep1007tanwar "what's the point in making a simple thing more and more correct?" FTFY. – davmac Jul 16 '16 at 10:38
0

Some important points:

First, Using scanf to read an int from user input usually allows for whitespace to be entered first:

scanf(" %d", &age);

In particular this skips over previous new line characters that were input previously and are still buffered.

Second, scanf returns a value indicating whether it succeeded or failed, and how many items it matched. You need to check this return value:

 int r = scanf(" %d", &age);
 if (r == EOF) {
     break;
 }
 if (r == 0) {
     printf("Error, retry: \n");         
 }

Third, if scanf can't match input it is left in the input buffer. If you don't retrieve it from the buffer, it will simply fail to match again the next time you call scanf, ad infinitum. For this reason, scanf is not great for handling user input at all. It is better, if possible, to read a single line of input into a buffer (you can use fgets for this, if you are careful), and then process the buffer. As a weak alternative, you can force some of the input buffer to be consumed by scanning for a string before you try to read the input value again:

 int r = scanf(" %d", &age);
 if (r == EOF) {
     break;
 }
 if (r == 0) {
     printf("Error, retry: \n");
     scanf("%*s"); // match string but suppress assignment
 }
 else {
     printf("Cool.\n");
     break;
 }

This modification gets your code to at least halfway-working state.

davmac
  • 20,150
  • 1
  • 40
  • 68
-1

Use do while Loop. Like:

Do{

// your code
Age = // asign value

}while(age>100 && age < 1);

So it will repeat until age is entered between 100 and 1. It will stop if it will get age b/w 1 - 100.

Thanks. Hope it will help.

Dr.Avalanche
  • 1,944
  • 2
  • 28
  • 37
Pirate
  • 2,886
  • 4
  • 24
  • 42