Click to See Complete Forum and Search --> : REALLY stupid question


MrNewbie
09-10-2001, 11:05 AM
In C, how can I get a single character from stdin without the newline becoming the gotten character? Whenever I use getc, or similar functions I end up having the newline as the character I got.
Is it better to try to get a while string and then check the first character of the character array?
Thanks

The Kooman
09-10-2001, 11:41 AM
Originally posted by MrNewbie:
<STRONG>In C, how can I get a single character from stdin without the newline becoming the gotten character? Whenever I use getc, or similar functions I end up having the newline as the character I got.
Is it better to try to get a while string and then check the first character of the character array?
Thanks</STRONG>


#include &lt;stdio.h&gt;

int main(void)
{
char c;

scanf(" %c", &c); /* note the space before the %c */
printf("c = .%c.\n", c);
return 0;
}

MrNewbie
09-10-2001, 12:24 PM
Ah sorry, that's the thing I forgot to mention. I don't like scanf because it is very error-prone so I was looking for a different way to do it.

MrNewbie
09-10-2001, 03:23 PM
On seconds thoughts, and second testing ;) that seems perfectly fine, usually when I use scanf ans enter the wrong kind of data expected then it goes into an infinite loop, but seemingly not here.

TheLinuxDuck
09-20-2001, 03:28 PM
MrNewbie:

I also dislike scanf.

Here is another method:

char getChar(void)
{
char buffer[3];
fgets(buffer,3,stdin);
fseek(stdin,0L,SEEK_END); // flushing stdin
if(*buffer!='\n') return *buffer;
return 0;
}


[ 20 September 2001: Message edited by: TheLinuxDuck ]

MrNewbie
09-21-2001, 07:33 AM
Thanks a lot!