C++实现从文件中读取数据并分别计算的代码

flowercuts 2011-11-17 05:08:53
我在学习C++有关文件I/O操作的章节时候遇到了一个习题,卡住了…:
说,写一个程序,要求从文件中读取信息,并按照每行前缀的符号实现其运算; 文件中的内容是:
+ 1 2
- 3 5
* 6 0
/ 6 0
/ 6 2
要求所写代码能具备一定错误处理机制 (比如文件I/O错误信息及相关计算可能出错的信息)。

希望有大牛帮助解决;同时也欢迎一切讨论或建议。
自觉遵守论坛纪律,请勿灌水、拍砖……
...全文
394 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2011-11-18
  • 打赏
  • 举报
回复
简单问题复杂化,楼主小心.
flowercuts 2011-11-18
  • 打赏
  • 举报
回复
谢谢洪哥和鼬的指点,问题解决了。顺便也把代码贴了出来,以供日后查考改正:
文件1: main.cpp
#include <iostream>
#include <cstdlib>
#include "FileBinaryOperators.h"

int main(int argc, char* argv[])
{
test();
return EXIT_SUCCESS;
}

文件2: FileBinaryOperator.h
#ifndef FILEBINARYOPERATORS_H_INCLUDED
#define FILEBINARYOPERATORS_H_INCLUDED

class BinaryOperator
{
public:
BinaryOperator (double op1, double op2) : fop1(op1), fop2(op2) {};
virtual ~BinaryOperator(){};
virtual double DoOp() const = 0;

protected:
const double fop1;
const double fop2;
};

class Adder : public BinaryOperator
{
public:
Adder (double op1, double op2) : BinaryOperator(op1,op2) {};
~Adder (){};
virtual double DoOp() const;
};

class Subtractor : public BinaryOperator
{
public:
Subtractor (double op1, double op2) : BinaryOperator(op1, op2){};
~Subtractor(){};
virtual double DoOp() const;
};

class Multiplier : public BinaryOperator
{
public:
Multiplier (double op1, double op2) : BinaryOperator(op1,op2) {};
~Multiplier(){};
virtual double DoOp() const;
};

class Divider: public BinaryOperator
{
public:
Divider (double op1, double op2) : BinaryOperator(op1,op2){};
~Divider(){};
virtual double DoOp () const;
};

void test();


#endif // FILEBINARYOPERATORS_H_INCLUDED

文件3: FileBinaryOperators.cpp
#include <iostream>
#include <stdexcept>
#include <vector>
#include <fstream>
#include <string>
#include "FileBinaryOperators.h"

double const DefaultOverflow = 1.0E10;
double const DefaultUnderflow = -1.0E10;

using std::cout;
using std::endl;
using std::vector;

double Adder::DoOp () const
{
double a = fop1 + fop2;
if(a<DefaultOverflow && a>DefaultUnderflow )
{
return fop1+fop2;
}
else
{
throw std::overflow_error ("OverflowError01: Check Adder.");
}
}

double Subtractor::DoOp() const
{
double a = fop1 - fop2;
if(a<DefaultOverflow && a>DefaultUnderflow)
{
return fop1-fop2;
}
else
{
throw std::overflow_error ("OverflowError02: Check Subtractor.");
}
}

double Multiplier::DoOp() const
{
double a = fop1*fop2;
if (a<DefaultOverflow && a> DefaultUnderflow)
{
return fop1*fop2;
}
else
{
throw std::overflow_error("OverflowError03: Check Multiplier.");
}
}

double Divider::DoOp() const
{
double a;
if(fop2 != 0 && a<DefaultOverflow && a> DefaultUnderflow )
return fop1/fop2;
else if (fop2 == 0)
throw std::runtime_error("Divided by 0 is undefined!");
else
throw std::overflow_error("OverflowError04: Check Division.");
}

void test()
{
vector<BinaryOperator*> binOp;
cout<<"Enter input file name:"<<endl;
std::string filename;
std::cin>>filename;

std::ifstream in_File(filename.c_str());
if(!in_File)
std::cerr<<"Can't open file: "<<filename<<", file doesn't exist or removed!"<<endl;
else
{
while(!in_File.eof())
{
try{
char opr;
double x,y;

in_File>>opr>>x>>y;
if(in_File.bad())
throw std::runtime_error("I/O stream currupted!");
switch(opr)
{
case '+':
binOp.push_back(new Adder(x,y));
break;
case '-':
binOp.push_back(new Subtractor(x,y));
break;
case '*':
binOp.push_back(new Multiplier(x,y));
break;
case '/':
binOp.push_back(new Divider(x,y));
break;
default:
throw std::runtime_error("Not invalid input.");

}
}
catch(std::runtime_error err)
{
std::cerr<<err.what()<<endl;
}

}

for(vector<BinaryOperator*>::iterator iter = binOp.begin(); iter != binOp.end(); ++iter)
{
try
{
cout<<(*iter) -> DoOp()<<endl;
}
catch(std::runtime_error err)
{
std::cerr<<err.what()<<endl;
}
catch (std::overflow_error excp)
{
std::cerr<<excp.what()<<endl;
}
delete *iter;
}
}


}
自由 2011-11-17
  • 打赏
  • 举报
回复
这种题目如果是面试题的话,衍生的就多了
柯大侠爱喝水 2011-11-17
  • 打赏
  • 举报
回复
+ 1 3
- 2 4
* 3 1
我是按中间空格来拆分的
柯大侠爱喝水 2011-11-17
  • 打赏
  • 举报
回复
测试过了,能用,我是按照你给的文件格式来写的,如果文件是这样制表的,你要把中间拆读出的串的方法改一下就行了
柯大侠爱喝水 2011-11-17
  • 打赏
  • 举报
回复
int account(char loge , int x , int y)
{
int SumValue;

switch (loge)
{

case '+' : SumValue = x + y;
break;
case '-' : SumValue = x - y;
break;
case '*' : SumValue = x * y;
break;
case '/' : SumValue = x / y;
break;
}
return SumValue;
}


int main()
{
int nResult;
char aReadFile[512] = {0};
FILE *fFileStream = NULL;

fFileStream = fopen("d:\\test.txt" , "rb");
if (!fFileStream)
{
cout<<"failed to open file!"<<endl;
return 1;
}
while (fgets(aReadFile , 511 , fFileStream))
{
char cOperator = aReadFile[0];
int nTemp_x = atoi(&aReadFile[2]);
int nTemp_y = atoi(&aReadFile[4]);
nResult = account(cOperator , nTemp_x , nTemp_y);
cout<<"x"<<cOperator<<"y"<<"="<<nResult<<endl;

}
fclose(fFileStream);
return 0;

}
hongwenjun 2011-11-17
  • 打赏
  • 举报
回复
#include <iostream>    // 数据流输入/输出
#include <fstream>
#include <string> // 字符串类
using namespace std;

int Calculate(char& algo, int& x , int& y); // 计算 +-*/
int main()
{
char algo;
int x , y;
ifstream fin("data.txt");

while (fin) {
fin >> algo >> x >> y;
fin.get(); // 加入这行,避免最后一行输出两次
cout << x << algo << y << "=" << Calculate(algo, x , y) << endl;
}

return 0;
}

int Calculate(char& algo, int& x , int& y)
{
int ret = -1;
switch (algo) {
case '+' : ret = x + y;
break;
case '-' : ret = x - y;
break;
case '*' : ret = x * y;
break;
case '/' : ret = x / y;
break;
}
return ret;
}

恨天低 2011-11-17
  • 打赏
  • 举报
回复
这题目虽然简单,但是如果是面试题的话,酷似《大话设计模式》中那题。。
hongwenjun 2011-11-17
  • 打赏
  • 举报
回复
#include <iostream>    // 数据流输入/输出
#include <string> // 字符串类
using namespace std;

int main()
{
char algo;
int x , y;
int ret;

cin >> algo >> x >> y;

switch (algo) {
case '+' : ret = x + y;
break;
case '-' : ret = x - y;
break;
case '*' : ret = x * y;
break;
case '/' : ret = x / y;
break;
}

cout << x << algo << y << "=" << ret << endl;
return 0;
}
LAST_MAN 2011-11-17
  • 打赏
  • 举报
回复
我也刚学完这章。.eof() .fail() .bad() a.clear()都需要用到吧

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧