Frage

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.

War es hilfreich?

Lösung

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).

Andere Tipps

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.
    }
}

You have at least two solution:

I.

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

II. get a from File Descriptor

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

Try this, this may help for you:

while(1) {
    scanf("%f",&a);
    if(a==EOF)
    break;
    ......
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top