如果我的代码中没有 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;
}
Run Code Online (Sandbox Code Playgroud)
clear()重置流上的错误标志(正如您可以在文档中阅读的那样)。如果您使用格式化提取,那么如果提取失败(例如,如果您尝试读取整数并且没有任何可解析的内容),则会设置错误标志“失败”。因此,如果您使用错误状态来终止循环,则必须在进入下一个循环之前使流再次可用。
但是,在您的特定情况下,您的代码写得不好并且违反了“最大局部性原则”。一个更理智的版本,作为奖励不需要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;
}
}
Run Code Online (Sandbox Code Playgroud)
有些人甚至会将外循环写为for (std::string temp; std::getline(readfile, temp); ) { /* ... */ },尽管其他人认为这种滥用。