Using fgets

Joined
Jan 24, 2022
Messages
7
Reaction score
0
hi,
just trying to input a word and returning the number of letters the word has.
For some reason, my i counter always gets to 1 higher than the actual number of letters.
Why is this happening? (i understand it is easier to use strlen but just want to know why this is happening).

#include <stdio.h>
int main(void) {
char input[1042] = {};
printf("Input word:");
fgets(input, 1042, stdin);
int i = 0;
while (input != '\0') {
i++;
}
printf("%d", i);
return 0;
}
 
Joined
Mar 3, 2021
Messages
240
Reaction score
30
Please use code tags next time, it turned into italics halfway through and dropped the array index bit. It's one greater because there's a newline character at the end of your input. Throw a line like the following at the beginning of your while loop to inspect it.
C:
printf("i = %d (%c)\n", i, input[i]);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top