Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to read stdin that may include newline?

Tags:

c

I have to write a program in C that handles the newline as part of a string. I need a way of handling the newline char such that if it is encountered, it doesn't necessarily terminate the input. So far I've been using fgets() but that stops as soon as it reaches a '\n' char. Is there a good function for processing the input from the console that doesn't necessarily end at the newline character?

To clarify:

I need a method that doesn't terminate at the newline char because in this particular exercise when the newline char is encountered it's replaced with a space char.


1 Answers

fgets gets a line from a stream. A line is defined as ending with a newline, end-of-file or error, so you don't want that.

You probably want to use fgetc. Here's a code example of a c program file fgetc.c

#include <stdio.h>

int main (void) {
  int c;
  while ((c = fgetc(stdin)) != EOF) fputc(c, stdout);
}

compile like this:

cc fgetc.c -o fgetc

use like this (notice the newline character '\n'):

echo 'Hello, thar!\nOh, hai!' | ./fgetc

or like this:

cat fgetc.c | ./fgetc

Read the fgetc function manual to find out more: man fgetc

like image 191
EhevuTov Avatar answered Oct 25 '25 00:10

EhevuTov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!