How can I complete the cycle after pressing the "Enter" key on vanilla C?

while(scanf("%d", var)!=EOF) printf("%d + %d = %d", var, var, 2*var) 

In extreme cases, you can use the posix-function.

  • And what scanf return if you just press Enter? Probably 0? - VladD 10:39 pm
  • Nothing, that's the problem. - StackOverflowRu
  • one
    uh ... he can't return "nothing", his return type is int . - VladD
  • @VladD scanf will wait until the user enters at least one non-whitespace character. - VisioN
  • @VisioN: sorry :-( - VladD

2 answers 2

In fact, the scanf feature will not allow you to enter numbers down to the empty line, since scanf will always wait for the number to be entered, ignoring all empty characters (spaces, tabs and new lines).

Therefore, it will be easier to implement everything through gets (or not deprecated fgets ):

 int main() { char s[32]; int n; while (fgets(s, sizeof(s), stdin) != 0 && *s != '\n') { n = atoi(s); // конвертация строки в число printf("%d + %d = %d\n", n, n, n * 2); } return 0; } 
  • one
    scanf will do what it asks for. In particular, you can force it to check the whitespace. - Qwertiy
 #include <stdio.h> int main(void) { int x; for (char *format="%d"; scanf(format, &x) == 1; format="%*[ ]%d") printf("%d + %d = %d\n", x, x, x+x); return 0; } 

It is assumed that you must enter at least one value.