If I type "abc" usingI get "3" which is correct. But when usingCode:scanf("%s" , s1); printf("%d\n" , strlen(s1));I always get the number of characters I type in +1. Why?Code:fgets(s1,10,stdin)
If I type "abc" usingI get "3" which is correct. But when usingCode:scanf("%s" , s1); printf("%d\n" , strlen(s1));I always get the number of characters I type in +1. Why?Code:fgets(s1,10,stdin)
You do type 'a', 'b', 'c' and ENTER, didn't ya?
Well... fgets() don't strip this final '\n'... Your string is "abc\n\0".
A more elegant solution I like to use to remove the trailing newline character is:
Code:s1[strcspn(s1, "\n")] = '\0';
I agree, but notice if there is no '\n' in the string, the final '\0' will be overwriten with '\0' again (this is unecessary)... I know, it works...
The strchr() approach changes '\n' only if it is found. (it is a little bit faster!).
Of couse it is more code in C, but if you want to write less code, one can write a simple macro or inline function:
And use it:Code:#define STRIPNL(s) { char *p; if ( p = strchr( (s), '\n' ) ) *p = '\0'; }
Code:STRIPNL(s1);
Last edited by flp1969; 04-26-2019 at 06:52 PM.
This is my favourite when it comes to fgets - Think about it this way: when will fgets not have a new line character? When it returns NULL - in that case you won't be doing the operation.
You can also add "\n\r" if the stream is binary.
Just a style thing here - I'd make stripnl a function, because macros are a pain in the ... when trying to debug - Especially when the code is large and written by someone else that has left the company...
Thanks! There is still another problem with using fgets. If I want to enter and store a password using fgets, it will add a 0 at the end of my password? How do I make it not count the 0 at the end?
The 0 is the null character used to terminate the string. It already isn't counted.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)