我已经编写了一个代码来获取输入文本文件中的所有表达式并计算它们 . 但问题是,它只是计算第一个表达式 . 而且如果我在文本文件中包含---------来分隔表达式,它将给我编译器错误 .
这是input.txt文件
罪(0)
cos(0)
pi = 3.14 radius = 3 sin(pi / 2)pi * radius ^ 2
1 2
10 - 5
3 * 4
12 / 4
2 ^ 3
//declaring input files
string inputLine;
ifstream file ("input.txt");
//looping through the file to get the expressions
while (std::getline (file, inputLine))
{
inputLine = trim (removeBackspaces (inputLine));
Parser p (inputLine);
double value = p.Evaluate ();
ofstream file;
file.open("output.txt");
file <<std::cout << "Result = " << value << std::endl;
file<<std::cout << "abc = " << abc << std::endl;
file<<std::cout<<"----------------------"<<endl;
file.close();
}
}
}
1 回答
每次从中读取行时都会关闭文件(这会打开文件,读取一行并关闭它) . 只需在
while
循环中删除file.close();
即可 .另外 - 除非你想将相同的
fstream
对象绑定到另一个文件,否则永远不需要手动关闭它,因为fstream
的析构函数会为你做这个 . 不需要明确地称之为 .