James
James

Reputation: 87

Add character to end of line in C

I'm sure there is a very simple answer to this question. However, I am trying to add a character to the beginning and the end of a line in C. I have the add at the beginning part down but am having issues with adding the add to the end part. Is there a simple solution just using the code I have? Thanks in advance

#include <stdio.h>

int main(void) {
   char c; // store a character

   printf("0");
   while (scanf("%c", &c) != EOF) {
      printf("%c", c);
      if (c == '\n') {
         printf("0");
      } // if
   } // while

   return 0;

} // main

Upvotes: 1

Views: 2431

Answers (1)

Dawood
Dawood

Reputation: 5306

You need to check for newline before printing the character, something like this:

while (scanf("%c", &c) != EOF) {
    if (c == '\n') {
        printf("0");
    }
    printf("%c",c);
}

This code will print your new character before the newline.

Upvotes: 4

Related Questions