I'll wait to see what the other people reading this thread have to say before giving you a good solution. :)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Number one I would change your expression to:
char expression;
and then call a %c in your scanf.
#include <stdio.h>
int main()
{
char expression;
while ((scanf("%c",&expression)) != EOF)
{
fprintf(stdout, "char->%c\n", expression);
}
return 0;
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
Why scanf ? Are you familiar with getchar ? It's better suited for your needs. With getchar , it's as simple as
while(c = getchar() != '\n')
Also, if I remember correctly, using a char to check for EOF is not going to work, for char is an unsigned data type, while EOF is a negative one.
creeps
Junior Poster in Training
82 posts since Jul 2010
Reputation Points: 85
Solved Threads: 8
>it is assumed that the user is entering single digit strings (such as "a 1 2 3 d"(enter))
If all you want is single character input, you don't even need scanf. Just use getchar and test for whitespace manually:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (isspace(ch))
continue;
printf("Processing '%c'\n", ch);
}
However, I have yet to see such a program that doesn't grow into more than single character words. In that case, scanf can be used without any problems provided the assumption holds that whitespace or end-of-file terminates each word.
One problem in this case is that scanf doesn't differentiate between newlines and other whitespace. It's all the same to scanf. But because scanf stops reading at whitespace, you can read the next character and see which one it was:
#include <stdio.h>
int main(void)
{
char word[512];
char next;
while (scanf("%511s%c", word, &next) >= 1) {
printf(">%s<\n", word);
if (next == '\n')
break;
}
return 0;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
I'm making a program that accept 1 character long strings (and ignores spaces " ") until a user presses return/enter.
So far I have,
int main(){
char expression[1];
while ((scanf("%s",expression)) != EOF){
//code
}
return 0;
}
it is assumed that the user is entering single digit strings (such as "a 1 2 3 d"(enter))
its seems to not like the while condition as it will keep accepting input even after I hit enter. I have tried using -1 instead of EOF but its the same output.
Any ideas?
I don't think anyone mentioned the potential for buffer overflow in the original program...That's why I mentioned changing the variable from a character array to a single character.
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387