Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
countofmontecristo Avatar asked Dec 15 '14 18:12

countofmontecristo


1 Answers

try

fgets(buffer, 100, stdin);
size_t ln = strlen(buffer)-1;
if (buffer[ln] == '\n')
    buffer[ln] = '\0';
like image 120
madz Avatar answered Sep 26 '22 06:09

madz