Reputation: 3
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!
Upvotes: 0
Views: 604
Reputation: 60047
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;
}
Upvotes: 1
Reputation: 181932
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.
Upvotes: 2