White Spirit <wh**********@n tlworld.com> writes:
I'm trying to use getchar() to read alphanumeric data as follows:-
char input[150];
/* Take a string of input and remove all spaces therein */
int j = 0;
while ((input[j] = getchar()) != '\n')
{
if (!isspace(input[j]))
j++;
}
/* Append the null character */
input[j] = '\0';
I'm aware there's no bounds checking at present - it's forms part of
test code at present. The problem is, I get unexpected behaviour when
reading digits. With Linux and Solaris, if the data starts with a
digit the programme hangs. With Linux, if the stream begins with an
alpha character, it works as intended but on the Solaris box I get
entirely different characters.
I've looked in books and on Google but nothing is specifically
mentioned about this. I assume that getchar() is intended for alpha
data only, which presumably means that using scanf would be better
with a separate function to remove the whitespace?
getchar() reads a single character from standard input. It doesn't
distinguish between alphanumeric characters and any other characters.
It's difficult to tell what's going wrong with your program because
you haven't shown us your program; you've only posted a code fragment.
getchar() returns either a character value (as an unsigned char
converted to int) *or* the special negative value EOF. You need to
store the result of getchar() in an int, not in a char. You also need
to check whether it returned EOF. In your code fragment, if you hit
end-of-file before seeing a '\n', you'll have an infinite loop.
Read section 12 of the C FAQ, <http://www.c-faq.com/>. If you're
still having problems, post a small, complete, compilable program that
illustrates whatever problems you're having. Be sure you have the
required #include directives for whatever functions you're using
(<stdio.h> for getchar(), <ctype.h> for isspace()).
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.