+ 1

Using strlen() in C.

I have this code: char input[100]; printf("%s", "Enter something: "); fgets(input, 100, stdin); int n = strlen(input); printf("%d", n); But, if I write for example the word memo, the output will be 5, why? it should be 4. I solved it doing this: printf("%d", n - 1); // Now is 4 if you use memo as input. But I'm not sure if this is the right solution, why if I write memo as input, returns me 5 instead 4? I tried the same function in C++, and I don't have this problem.

12th Oct 2018, 10:23 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
1 Antwort
+ 2
fgets() inputs a trailing newline character. You should use strcspn() to fix this: input[strcspn(input, "\n")] = 0;
12th Oct 2018, 11:01 PM
qwerty
qwerty - avatar