c++ - clear() 是做什么的?

标签 c++ g++

如果我的代码中没有 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/

相关文章:

接受 array.begin() 和 array.end() 作为参数的 C++ 函数

linux - 在 Linux 上使用静态链接构建应用程序是否明智?

c++ - 在 C++ 中的类声明中初始化 const 成员

c++ - 在 TinyXML 中解析 <multi_path literal ="not_measured"/>

c++ - Boost协程断言失败

C++, boost : how to fill buffer and transfer (image) file data over network?

c++ - 非标准语法;使用 '&' 创建一个指针成员。显示函数 C++ 出错

c++ - R:dyn.load 错误(文件,DLLpath = DLLpath,...)

c++ - g++ 是否不从它存在的第一个包含路径中获取头文件?

c++ - 为什么某些编译器拒绝作为指针传递的匿名对象?