第五次作业--计算器项目之学习文件读取方式

一.

传送门: github problem

参考资料: fstream 相对路径与绝对路径

Code:

main.cpp

int main (int argc, char *argv[])
{    

    Print Put;    
    string str;   // 定义 str 用来存储表达式。

    bool flag=false; //判断是否为文件输入输出形式 
    string s=argv[1];    

    if(s == "-a") // 输出表达式以及结果 
    {
    	str = argv[2];
    	cout << str << " ";
    	Put.print_str(str,flag,"","");	//计算,输出 
    }
    else if(s == "-f") // 文件输入/输出 
    {
    	str="";
    	string input_txt = argv[2]; 	//输入文件路径 
    	string output_txt = argv[3];	//输出文件路径 
    	flag = true;  
    	Put.print_str(str,flag,input_txt,output_txt);
    }
    else 
    {
    	str = argv[1];	//直接输出结果 
    	Put.print_str(str,flag,"","");
    }
    return 0;
}

Print.cpp

void Print::print_str( string str, bool flag , string input_txt, string results_txt)
{
    Calculation cal; //计算 
    Scan Calculator;   // 对象实例化
    queue<string>Que;

    if(!flag)
    {
    	    Que=Calculator.ToStringQueue(str); //调用。
    		string result = cal.calculation(Que);//计算 
    		if ( j != 0 )   
    		{
    		    cout << "Error!" <<endl;
    		}
    		else
    		{
    		    cout  << result << endl;  
    		}		
    }
    else 
    {
    	ifstream in; //声明 
    	ofstream out;
    	
    	//文件打开 
    	in.open(input_txt.c_str(), ios::in); 	
    	out.open(results_txt.c_str(), ios::out);
    	
    	//读入文件 
    	while(!in.eof())  
    	{
    		getline(in,str,'\n'); //从文件中读取字符串 
    		Que=Calculator.ToStringQueue(str); //调用。
    		string result = cal.calculation(Que);//计算 
    		
    		// out << 表示向文件写入结果 
    		if ( j != 0 )
    		{
    		    out << "Error!\n";
    		}
     		else
    		{
    		    out  << result << endl;  
    		}
    	}
    	in.close(); //文件关闭 
    	out.close();
    }
    return ;
};

三.

解题思路:

  • 1.为避免main.cpp的代码臃肿性,将字符串处理以及计算输出置于Print中调用.
  • 2.定义bool flag判断是否为-f指令,从而进行相应的计算处理以及输出.
  • 3.-f指令处理:
    • 声明:
      ifstream in; //输入文件
      ofstream out;//输出文件

    • 文件打开:
      in.open(input_txt.c_str(), ios::in); out.open(results_txt.c_str(),ios::out);

    • 1.从文件中读取字符串 :
      getline(in,str,'\n');//存入str中,遇'\n'停止;

      2.调用Scan以及Calculation类处理计算str,返回值赋予result;

      3.将结果输出到文件:
      out << result << endl;

    • 文件关闭:
      in.close();
      out.close();


四.

运行结果(截图):


程序结构框图:




In The End

posted on 2016-05-07 11:58  wish_forever  阅读(280)  评论(4编辑  收藏  举报

导航