what does clear() do?

what does clear() do?

本文关键字:do does clear what      更新时间:2023-10-16

如果我的代码中没有istring.clear.(),输出将是"nan%"。一切都运行良好,如果它在那里,输出是60%。它到底有什么用?为什么会有不同呢?(注:我的输入是"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()重置流上的错误标志(您可以在文档中阅读)。如果你使用格式化的提取,那么错误标志"fail"将被设置,如果提取失败(例如,如果你试图读取一个整数,没有任何可解析的)。因此,如果您使用错误状态来终止循环,则必须在进入下一个循环之前使流再次可用。

在你的特殊情况下,你的代码写得很糟糕,违反了"最大局部性原则"。一个更合理的版本,作为奖励不需要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); ) { /* ... */ },尽管其他人认为这是滥用。