13

I'm trying to write an inputted string elsewhere and do not know how to do away with the new line that appears as part of this string that I acquire with stdin and fgets.

 char buffer[100];
 memset(buffer, 0, 100);
 fgets(buffer, 100, stdin);
 printf("buffer is: %s\n stop",buffer);

I tried to limit the amount of data that fgets gets as well as limiting how much of the data is written but the new line remains. How can I simply get the inputted string up to the last character written with nothing else?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
countofmontecristo
  • 381
  • 3
  • 5
  • 15
  • `scanf("%99[^\n]%*c", buffer);` – BLUEPIXY Dec 15 '14 at 18:51
  • @BLUEPIXY `scanf("%99[^\n]%*c", buffer)` will not read anything into `buffer` if the first `char` is `'\n'`. The `'\n'` remains in `stdin`. – chux - Reinstate Monica Dec 15 '14 at 20:07
  • 2
    Do you want to read a line and leave the `'\n'` in the input stream, or do you want to read a line including the `'\n'` and then discard the `'\n'`? (This will affect the next input operation, which will or will not see the `'\n'` waiting for it.) – Keith Thompson Dec 15 '14 at 20:13

2 Answers2

5

try

fgets(buffer, 100, stdin);
size_t ln = strlen(buffer)-1;
if (buffer[ln] == '\n')
    buffer[ln] = '\0';
madz
  • 1,803
  • 18
  • 45
5

Simply look for the potential '\n'.

After calling fgets(), If '\n' exists, it will be the last char in the string (just before the '\0').

size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
  buffer[--len] = '\0';
}

Sample usage

char buffer[100];
// memset(buffer, 0, 100); not needed
if (fgets(buffer, sizeof buffer, stdin) == NULL) { // good to test fgets() result
  Handle_EOForIOerror();
}
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
  buffer[--len] = '\0';
}
printf("buffer is: %s\n stop",buffer);

Notes:

buffer[strlen(buffer)-1] is dangerous in rare occasions when the first char in buffer is a '\0' (embedded null character).

scanf("%99[^\n]%*c", buffer); is a problem if the first char is '\n', nothing is read and '\n' remains in stdin.

strlen() is fast as compared to other methods: https://codereview.stackexchange.com/a/67756/29485

Or roll your own code like gets_sz

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256