if I don’t have istring.clear.() in my code, the output would be “nan%”. everything works well and output is 60% if it’s there. What does it really do there? why it makes a difference? (p.s my input is “y n y n y”)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
//inline function
inline ifstream& read(ifstream& is, string f_name);
//main function
int main ()
{
string f_name=("dcl");
ifstream readfile;
read(readfile, f_name);
string temp, word;
istringstream istring;
double counter=0.0, total=0.0;
while(getline(readfile,temp))
{
istring.str(temp);
while(istring>>word)
{
if(word=="y")
++counter;
if(word=="n" || word=="y")
++total;
}
istring.clear();
}
double factor=counter/total*100;
cout<<factor<<"%"<<endl;
return 0;
}
inline ifstream& read(ifstream& is, string f_name)
{
is.close();
is.clear();
is.open(f_name.c_str());
return is;
}
clear()resets the error flags on a stream (as you can read in the documentation). If you use formatted extraction, then the error flag “fail” will be set if an extraction fails (e.g. if you’re trying to read an integer and there isn’t anything parsable). So if you’re using the error state to terminate the loop, you have to make the stream usable again before going into the next loop.In your particular case, though, your code is just poorly written and violates the “maximum locality principle”. A saner version, that as a bonus doesn’t require
clear(), would be like this:Some people would even write the outer loop as
for (std::string temp; std::getline(readfile, temp); ) { /* ... */ }, though others consider this abuse.