0

This program is suposed to verify that the user input a integer. Give back an error if the datatype is incorect or if the input is empty. But only one time. I want to transform this program to keep asking the user until the answer is good.Here its a "single-use" programs , but i want it to do it with a while but its infinite.

    #include <stdio.h>

    int main()
      {
    int num;
    char term;

    if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    {
        printf("failure\n");
    }
    else 
    {
        printf("valid integer followed by enter key\n");
    }

    return 0;
    }
  • 2
    What part you don't understand? – Cid Nov 16 '20 at 13:08
  • 1
    Start by reading: http://www.cplusplus.com/reference/cstdio/scanf/ – Fiddling Bits Nov 16 '20 at 13:11
  • 1
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). So that should be the next character. It's flawed though, because you don't have to input one per line for `scanf()` to work correctly. If there are 3 iterations then `scanf()` will work when they are all input on the same line. So really, the next character test should be for whitespace using `!isspace(term)`. – Weather Vane Nov 16 '20 at 13:25
  • 1
    just use `while/do while` and pass your condition to it then loop will continue till user enter the proper(As per requirement) input – Adam Strauss Nov 27 '20 at 13:18

2 Answers2

2

"...it work fine but i can't understand it.Can you please explain me?"

The scanf() function is the core of this piece of code.

scanf() returns the number of items successfully converted. In this example the program is attempting to convert 2 items, so checking that return is == 2 will confirm call was successful. Explicitly, the coder's intent appears to be to verify that the numeric value and the newline are captured. For this simple example, this code is sufficient, but scanf() is capable of more. At the same time, there are arguably better alternatives for user input.

ryyker
  • 22,849
  • 3
  • 43
  • 87
1

Let me try: I didn't touch C++/C since 5 years so forgive my syntax errors.

Do-while:

#include <stdio.h>

int main()
{
    int num;
    char term;
    
    do{
        user_input = scanf("%d%c", &num, &term)
        //Code for wrong input
     }
    while(user_input != 2 || term != '\n')
    //Code for right input

    return 0;
}

While:

#include <stdio.h>
    
int main()
{
    int num;
    char term;
  
    user_input = scanf("%d%c", &num, &term)
    while(user_input != 2 || term != '\n')
    {
        //Code for wrong input
        user_input = scanf("%d%c", &num, &term)  //In while loop you've to take input again
    }
    //Code for right input
    return 0;
}
Adam Strauss
  • 1,889
  • 2
  • 15
  • 45