You're creating an empty string (line)....and setting its length to the
len variable. As you then put strings into your line, the len variable
is never recalculated...it remains at what it started at i.e. 0. In
other words, the len variable doesn't dynamically update itself every
time you're line changes...you need to explicitly recalculate the
string length each time...ie.
while(getline(in,line))
{
len = line.length();
cout<< line <<'\n';
cout<<len<<endl;
}
ricky wrote:
What is worng with my code.
I can reads all the lines all right but it doesn't return me the length
of lines.
It returns 0 for each line
#include <fstream>
#include <istream>
#include <iostream>
#include <ostream>
#include <string>
int main()
{
fstream in("example.txt");
static string line;
int len = line.length();
while(getline(in,line))
{
cout<< line <<'\n';
cout<<len<<endl;
}
return 0;
}