You get a too small result because the line endings in your text file are encoded in a different way than the convention on your system.
Save or recreate the file with correct line endings for your system.
In the other direction, towards a too high result, the presented code
while(in)
{
getline(in,str);
j++;
}
… would produce a count of 1 for an empty file.
Instead do
while( getline(in,str) )
{
j++;
}
Note: this remark only covers correctness, not efficiency.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…