This question already has an answer here:
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?
Simply look for the potential
'\n'
.After calling
fgets()
, If'\n'
exists, it will be the lastchar
in the string (just before the'\0'
).Sample usage
Notes:
buffer[strlen(buffer)-1]
is dangerous in rare occasions when the firstchar
inbuffer
is a'\0'
(embedded null character).scanf("%99[^\n]%*c", buffer);
is a problem if the firstchar
is'\n'
, nothing is read and'\n'
remains instdin
.strlen()
is fast as compared to other methods: https://codereview.stackexchange.com/a/67756/29485Or roll your own code like
gets_sz
try