清除()有什么作用?
如果我的代码中没有 istring.clear.() ,则输出将为“nan%”。一切正常,输出为 60%(如果有的话)。它在那里到底有什么作用?为什么它会有所不同? (ps我的输入是“ynyn 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
clear()
重置流上的错误标志(正如您可以在 文档)。如果您使用格式化提取,那么如果提取失败(例如,如果您尝试读取整数并且没有任何可解析的内容),则会设置错误标志“失败”。因此,如果您使用错误状态来终止循环,则必须在进入下一个循环之前使流再次可用。但是,在您的特定情况下,您的代码写得不好并且违反了“最大局部性原则”。一个更明智的版本,作为奖励不需要
clear()
,会是这样的:有些人甚至会将外循环写为
for (std::string temp; std: :getline(readfile, temp); ) { /* ... */ }
,尽管其他人认为这种滥用。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.