如何在文本文件中逐行读取字符串?

时间:2019-01-07 17:38:24

标签: c++

此代码只会读取并计算input.txt文件中的第一个输入,而忽略输入文件中的其余输入。我一直在尝试解决它,以便它可以读取所有其余输入,并且计算它们。 这是我的代码,我认为这有问题。

我尝试了几种循环方法

int main()
{
  string inputLine;

  ifstream file ("input.txt");// input file to be read
  ofstream file1;
  file1.open("output.txt");


  freopen("output.txt", "w", stdout);// store all the output to this file

  while (std::getline (file, inputLine)) // read the strings in the input file
  {
    if( strncmp( "----", inputLine.c_str(), 4 ) == 0 )
      continue;

    //calculating binary and hexadecimal values
    char *opr = "^+-/%*=,()";
    std::string::iterator end_pos = std::remove(inputLine.begin(), 
    inputLine.end(), ' ');
    inputLine.erase(end_pos, inputLine.end());
    string str=inputLine;
    string str2="";
    int length=str.length();
    char t[length];
    str.copy(t, length);
    t[length] = '\0';
    char* tok;
    char *cop=new char [length];
    str.copy(cop,length);
    char *w = strtok_fixed( t, opr );

    while (w!=NULL)
    {
      string w2=w;
      std::stringstream tr;
      tr << w2;
      w2.clear();
      tr >> w2;
      int x=w2.length();
      int y=x-3;

      string check= w2.substr(0,3);
      string check1=w2.substr(0,x);

      if(check.find("0x") != std::string::npos)
      {
        unsigned int x= strtol(w2.c_str(), NULL, 0);
        std::ostringstream s;
        s << x;
        const std::string ii(s.str());
        str2=str2+ ii;
      }
      else if (check1.find("b")!=std::string::npos)
      {
        w2.pop_back();
        long bin=std::strtol(w2.c_str(),0,2);
        std::ostringstream s2;
        s2<<bin;
        const std::string t2(s2.str());
        //inputLine.replace(inputLine.find(w2),(w2.length()+1),t2);
        str2=str2+t2;
      }
      else
      {
        str2=str2+w2;
      }
      char a =cop[w-t+strlen(w)];
      string s1="";
      s1=s1+a;
      std::stringstream tr1;
      tr1 << s1;
      s1.clear();
      tr1 >> s1;

      str2=str2+s1;
      w = strtok_fixed (NULL, opr);
    }

    //str2 should be taken to the parser for final evaluations
    Parser p(str2);
    double value = p.Evaluate ();
    std::cout<<"----------------------"<<endl;
    std::cout << "Result = " << value << std::endl;

    std::cout<<"----------------------"<<endl;

    return 0;
  }
}

1 个答案:

答案 0 :(得分:2)

问题出在最后

return 0;
 }

 }

应该是

 }
return 0;

 }

您从while循环内部返回,而不是在while循环结束之后返回。

您应该花一些时间正确缩进代码。这将帮助您发现这种错误。您还应该学习将代码分解为较小的功能。同样,这将帮助您更好地理解自己的代码。