user3376620
user3376620

Reputation: 85

Breaking while loop by EOF

I am trying to solve this problem and I need your help.

I have this code...

while(a != EOF){
  scanf("%f",&a);
  ...
}

...and I want to terminate this loop by pressing CTRL+D. It works but I need to press it two times. I tried to use this

while(getchar() != EOF){
  scanf("%f",&a);
  ...
}

but the same result. Is there any way to end this loop by pressing CTRL+D only once? Thank you for any response.

Upvotes: 2

Views: 18568

Answers (5)

Abhijeet Srivastava
Abhijeet Srivastava

Reputation: 1

Try this, this may help for you:

while(1) {
    scanf("%f",&a);
    if(a==EOF)
    break;
    ......
}

Upvotes: 0

Mauren
Mauren

Reputation: 1975

Try testing the return from scanf(): if your stream has ended it'll return EOF.

Upvotes: 0

dreamlax
dreamlax

Reputation: 95405

You should be checking the result of the call to scanf, not just for EOF, but also to ensure that the value parsed correctly. scanf returns the number of items that were successfully scanned, in your particular case, it will return 1 if it successfully scanned one float. If the parse was unsuccessful, then you can't rely on the value of a after that.

int result;
do
{
    while ((result = scanf("%f", &a)) != EOF)
    if (result == 1)
    {
        // scan was successful, you can safely use the value of "a"
    }
    else
    {
        // scan was unsuccessful
        // you can skip to the next line, produce an error, etc.
    }
}

Upvotes: 2

PersianGulf
PersianGulf

Reputation: 2885

You have at least two solution:

I.

while (scanf("%f",&a) != EOF) { ... }

II. get a from File Descriptor

Upvotes: 0

Gassa
Gassa

Reputation: 8874

You can check for EOF directly in scanf:

while (scanf("%f",&a) != EOF) {
    ...
}

For more information, read the docs on scanf (an example of them).

Upvotes: 2

Related Questions