Add Newline at the End of an Integer Using Putchar() (C Programming)?

I'm new to C programming, and I'm trying to figure out how I can add a newline ("\n") after printing an int value using the putchar() function. In "The C Programming" book by K&R, they provide the script below, but all characters are printed on the same line. How can I modify the code to print one character per line?

#include <stdio.h>

void main() {
int c;

c = getchar();
while (c != EOF) {
    putchar(c);
    c = getchar();
 }
}

I know I could use printf() with something like this:

printf("%d\n", c);

But I am wondering if C programming and the putchar() function have something like:

putchar(str(c)+"\n");

Kinda the same way you would do it in, say, python. Thanks!

8

1 Answer

The putchar function only writes a single character at a time. If you want to print a newline after each character, add an extra call to putchar, giving it the newline character:

putchar(c);
putchar('\n');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest