Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

c - Removing trailing newline character from fgets() input

I am trying to get some data from the user and send it to another function in gcc. The code is something like this.

printf("Enter your Name: ");
if (!(fgets(Name, sizeof Name, stdin) != NULL)) {
    fprintf(stderr, "Error reading Name.
");
    exit(1);
}

However, I find that it has a newline character in the end. So if I enter John it ends up sending John . How do I remove that and send a proper string.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps the simplest solution uses one of my favorite little-known functions, strcspn():

buffer[strcspn(buffer, "
")] = 0;

If you want it to also handle ' ' (say, if the stream is binary):

buffer[strcspn(buffer, "
")] = 0; // works for LF, CR, CRLF, LFCR, ...

The function counts the number of characters until it hits a ' ' or a ' ' (in other words, it finds the first ' ' or ' '). If it doesn't hit anything, it stops at the '' (returning the length of the string).

Note that this works fine even if there is no newline, because strcspn stops at a ''. In that case, the entire line is simply replacing '' with ''.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...