My problem is as follow: I need scanf to read multiple lines of user input. The user can input any combination of characters separated by whitespace or newline characters. My objective is to take each input that is separated by whitspace or newlines, and process it and output via printf. However, I am not allowed to store multiple inputs at once. My issues is this: every time the user presses enter, the scanf reads the entire line since I have scanf in a while loop != EOF. However, I don't want the scanf to read all lines of input until the user presses EOF. Is this possible? Here are some examples below:
Some pseudo code:
User Input:
cat dog mouse rabbit
snake dog
pink bob
joke*/
//Some pseudo code:
char input[100];
while (scanf("%s", input) != EOF) {
printf("%s", input);
}
In summary, I don't want scanf to read when the user presses enter since if it does, then the printf will activate but still allow the user to input stuff in. Is there a way to bypass this? Note: I have to use scanf and I can't store multiple separate inputs (like dog or cat) in a single array. Thank you.
%s
withscanf()
says "I don't care about white space". If you do care about white space, you probably shouldn't be usingscanf()
at all and certainly shouldn't be using%s
. You might be using%[…]
(a scan set) or%[^…]
(a negated scan set), but even that's problematic. – Jonathan Lefflerscanf
? Is this some kind of homework, with constraints? I'm a professional C programmer, I've been a professional C programmer for 35 years, and not only would I not usescanf
to solve this problem, I never usescanf
at all. It's usually significantly harder to do any kind of interesting input processing withscanf
than it is to use other, better techniques. (If this is a homework assignment and you have no choice, you have my sympathy.) – Steve Summit