Terminate program with enter/ EOF

Asked

Viewed 161 times

-1

I need the code to end after an empty enter, with no input or the 'EOF', but I don’t know how to apply it and I didn’t understand very well the examples I saw. The program is almost complete, it asks to stay in a cycle to read 2 numbers and show the sum of them, but precisely because of the 'empty enter' he enters "Time limit exceeded". The code

#include <stdio.h>
 
int main() {
    int n1, n2, sum;
    
    do{
        scanf("%d %d", &n1, &n2);
        sum = n1 + n2;
        printf("%d\n", sum);
    }while((scanf("%d %d", &n1, &n2) != '\n'));
    
    return 0;
}

Thanks in advance

  • You quoted that you got a "Time Limit Exceeded". Therefore, this code is an answer to a programming problem in the URI Online Judge/Hackerrank/etc style, correct?

2 answers

0

do{
    scanf("%d %d", &n1, &n2);
    sum = n1 + n2;
    printf("%d\n", sum);
}while((scanf("%d %d", &n1, &n2) != '\n'));

Do you have a book about C? a manual?

Read something about scanf()? You can try here in Microsoft Docs

It says

int scanf(
   const char *format [,
   argument]...
);

scanf() returns a int with the total read values, or EOF --- (-1) --- and you should use ALWAYS. Or better: should always use unless it is not important to know if you read something.

In your program used only once and in a strange way: you are trying to read two values:

scanf("%d %d", &n1, &n2)

then scanf() will return what? -1 to EOF, zero, 1 or 2. And you will compare with what? '\n' Which happens to be worth 10. So it is not strange that your program stays in this loop for all eternity.

And why didn’t you test at first reading if you read two values? Do you think it will be all right if the guy type one? or none? Won’t go.

And noticed in the loop will never add up the even series?

Your program reads the first pair and sums up. There reads the second pair and the third before adding up. There goes the second. And there read the fourth and fifth before adding: there goes the fourth pair...

That’s if the guy actually types one pair at a time...

Tested it out?

  • Note that according to the documentation: "If the input ends before the first Conversion (if any) has completed, and without a matching Failure having occurred, EOF Shall be returned."

0

Try something from the guy:

#include <stdio.h>
int main() {
    int n1=0, n2=0, sum;
    do{
        sum = n1 + n2;
        printf("%d\n", sum);
    } while((scanf("%d %d", &n1, &n2) != EOF));
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.