I'm brand new to C and am trying to learn how to take a string and print it using a function. I see examples everywhere using while(ch = getchar(), ch >= 0)
, but as soon as I put it into a function (instead of main()), it ceases to work. Right now, it's stuck in an endless loop... why is that?
// from main():
// printString("hello");
void printString(char *ch)
{
while (*ch = getchar(), *ch >= 0)
putchar(*ch);
}
getchar()
reads user input from stdin. If you want to print the string being passed in then there's no need for getchar()
.
Let's take it step by step. The loop you have reads one character a time from stdin until it reaches end-of-file. That's what the ch >= 0
test checks for: keep reading as long as we're getting valid characters. For printing the characters of a string, the condition changes. Now a valid character is anything that's not NUL ('\0'
). So we'll change the loop condition to:
while (*ch != '\0')
Next is figuring out the loop body. putchar(*ch)
is fine; we'll leave that there. But without getchar()
we have to figure out what the equivalent statement to "get the next character" is.
That would be ch++
. This advances the ch
pointer to the next character in the string. If we put that at the end of the loop then we'll print a character, advance one space, and then check if the next character is non-NUL. If it is then we print it, advance, and check.
while (*ch != '\0') {
putchar(*ch);
ch++;
}