如果我的代码中没有 istring.clear.(),输出将为“nan%”。一切正常,输出为 60%(如果存在)。它在那里真正做什么?为什么会有所作为? (p.s 我的输入是“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()
重置流上的错误标志(如您在 documentation 中所读)。如果您使用格式化提取,那么如果提取失败(例如,如果您尝试读取一个整数但没有任何可解析的内容),将设置错误标志“失败”。因此,如果您使用错误状态来终止循环,则必须在进入下一个循环之前使流再次可用。
但是,在您的特定情况下,您的代码编写得不好并且违反了“最大局部性原则”。一个更明智的版本,作为奖励不需要 clear()
,会像这样:
std::string temp;
while (std::getline(readfile, temp))
{
std::istringstream iss(temp);
std::string word;
while (iss >> word)
{
std::cout << word << "_" << std::endl;
if (word == "y") ++counter;
if (word == "y") ++total;
}
}
有些人甚至会把外层循环写成 for (std::string temp; std::getline(readfile, temp); ) {/* ... */}
考虑这种滥用行为。
关于c++ - clear() 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079333/