How can I get a string from input without including a newline using fgets?

countofmontecristo picture countofmontecristo · Dec 15, 2014 · Viewed 22.8k times · Source

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?

Answer

madz picture madz · Dec 15, 2014

try

fgets(buffer, 100, stdin);
size_t ln = strlen(buffer)-1;
if (buffer[ln] == '\n')
    buffer[ln] = '\0';