Search code examples
cstringchargetcharputchar

Printing a string in C using a function


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);
}

Solution

  • Based on your description, you just want:

    void printString(char *ch)
    {
      while(*ch) {
         putchar(*ch);
         ch++;
      }
    }
    

    Your original function:

    void printString(char *ch)
    {
        while (*ch = getchar(), *ch >= 0)
        putchar(*ch);
    }
    

    Does a lot of stuff:

    1. reads characters from stdin
    2. stores the character read from stdin into the first char pointed to by ch (this might not even work if you pass in a string literal.
    3. writes characters to stdout.
    4. Terminates when the read character is < 0 (this won't work on some platforms. Since the result is stored in a char you can't distinguish between EOF and a valid character. ch should be an int, as getchar() returns an int so you can check for EOF)