0

What is the problem in the code here?

#include <stdio.h>
#include <stdlib.h>

void main() {
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    int a = 5, b = 8;
    int inputs;
    printf("Guess value of a: \n");
    scanf("%d\n", &inputs);
    while (inputs > 0){
        if(inputs == a){
                printf("Correct!\n");
                break;
            }
            else{
                printf("Wrong!Try again!\n");
                scanf("%d\n", &inputs);
            }
    }

}

I am just trying the if stuff but the program takes 2 inputs first (before trying the while loop or the if test), and then examines the value of the first input. For example, if I type 1 and then 2, it checks the 1 first, says it is wrong, and goes on to demand a new input (say 3) but checks 2 on the next iteration.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Elegalaxy
  • 1
  • 4
  • what's your expectation? – Md Golam Rahman Tushar Mar 04 '20 at 05:07
  • Also, unless this is a *freestanding* system without an OS, then `void main()` is an incorrect declaration for `main()` See: [C11 Standard - §5.1.2.2.1 Program startup(p1)](http://port70.net/~nsz/c/c11/n1570.html#5.1.2.2.1p1). But note: In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. See: [C11 Standard - 5.1.2.1 Freestanding environment](http://port70.net/~nsz/c/c11/n1570.html#5.1.2.1) – David C. Rankin Mar 04 '20 at 05:15
  • 1
    The major problem is the trailing newline in the `scanf()` format — a diabolical UX trap. See [What is the effect of trailing white space in a `scanf()` format string?](https://stackoverflow.com/q/19499060/15168) for the sordid details. – Jonathan Leffler Mar 04 '20 at 05:30
  • You nailed that one -- my eyes just skimmed right over the `'\n'`. – David C. Rankin Mar 04 '20 at 05:33
  • @JonathanLeffler My senior found this problem and explain it to me after I posted this question. Thanks for the explanation. – Elegalaxy Dec 23 '21 at 07:06

0 Answers0