0

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

  • So do basic debugging. Run your program in a debugger and trace it as it runs to see why/where the extra increment comes from. [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – kaylum Apr 07 '22 at 23:34
  • Does *anyone* ever read [the online documentation](https://stackoverflow.com/editing-help) anymore about how to post formatted code before just splaying text into the editor and hitting the post button ? Regardless, `I` is never set to any value, and is the only thing printed. That by itself invokes *undefined behavior*. – WhozCraig Apr 07 '22 at 23:35
  • Is there a reason you don't just use `strlen(nameArr)`? – Barmar Apr 07 '22 at 23:39
  • You declared the variable `I` but then used the variable `i` in the loop. C is case-sensitive, they're not the same variables. – Barmar Apr 07 '22 at 23:41
  • when I use 'strlen(nameArr)' the calculated size is 2 numbers greater than the real size, so I used for loop to remove '\n' from the end. I think when I read a string from the file it comes with one white space and one '\n' – Faram Aboutalebi Apr 08 '22 at 00:34
  • when I run your code with file withe first line "6 5 6" I get the answer 5, that seems correct to me. Whats the problem? You dont need that `=' '` stuff – pm100 Apr 08 '22 at 00:58
  • Best guess -- you have CR (carriage return -- `'\r'`) characters in your text file from windows or some such that you're seeing (and counting). That's almost always the source of this kind of off-by-one error. – Chris Dodd Apr 08 '22 at 01:47
  • Your condition should be nameArr[i] != '\0' && nameArr[i] != '\n'&& nameArr[i] != '\r' as @ChrisDodd mentioned – Zouhair Dre Apr 08 '22 at 08:04

1 Answers1

0

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

pm100
  • 48,078
  • 23
  • 82
  • 145