0
void main(void)
{
    char character;

    do {
        scanf("%c", &character);
        printf("%c", character);
    } while (character != EOF);
}

I'm going to process the input character by character, and I am only allowed to use scanf(). However, the while loop does not stop. Since I may need to process the input with multiple-line strings, it is impossible to add one more condition: character != '\n'. Can somebody help me with this problem? Thanks!

Harold
  • 3
  • 1
  • You should also look at this question [scanf-leaves-the-new-line-char-in-buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer) which as the answers say can be solved by placing a space before `%c`, to filter out leading whitespace. For example `scanf(" %c", &character);` Some other format specifiers like `%d` and `%f` and `%s` do that automatically, but `%c` does not. – Weather Vane May 14 '18 at 20:21
  • Curious, does the loop stop if you type in `ÿ`? – chux - Reinstate Monica May 14 '18 at 20:22

2 Answers2

2

You have an incorrect expectation. When scanf() encounters the end of the input before either matching an input item or recognizing a matching failure, it returns EOF. Under no circumstance does it modify the value of the datum associated with an input item that has not been matched.

You are ignoring scanf's return value, which is generally a perilous thing to do, and instead testing whether scanf records EOF in the object associated with the input item, which, in your particular case, it must not ever do.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

For a start it should be int main...

Also you need to check the return value from scanf - please read the manual page.

Taking this into account, the code should look like this

#include <stdlib.h>
#include <stdio.h>
int main()
{
    char character;

    while (scanf("%c", &character) == 1) {
       if (character != '\n) {
         printf("%c", character)
       }
    }
    return EXIT_SUCCESS;
}
Ed Heal
  • 59,252
  • 17
  • 87
  • 127