I wrote the following code to read the first line of the text file and calculate the size of that string, but the calculated size is 1 number greater than the real size that I see on the text file. For example, this string: SAM, my code calculates the size 4; however the size of SAM is 3 or for Hello my code calculates the size 6, I'm wondering what is wrong with my code:
FILE * inp = fopen("name.txt", "r");
char nameArr[30];
fgets(nameArr, 30, inp);
int i;
for(i = 0; nameArr[i] != '\0' && nameArr[i] != '\n'; i)
{
}
if(nameArr[i-1] == ' ')
--i;
printf("i is %d\n", i);
fclose(inp);
I think the problem if here if(nameArr[i-1] == ' ')
but I cannot fix it
CodePudding user response:
I suspect you mean
int i; <<<=== i here
for(i = 0; nameArr[i] != '\0' && nameArr[i] != '\n'; i)
{
}
if(nameArr[i-1] == ' ')
--i;
printf("i is %d\n", i); <<<=== i here
There must be another i declared somewhere too, in which case change the name of this i something else