![](/img/trans.png)
[英]C++ : Read(Write) from(to) a file if provided otherwise fall back to std::cin (std::cout)
[英]read and write from files or from cin and cout
当 argc 为 1 时,我的代码运行良好,但是当我尝试从文件中读取和写入时(当 argc 为 3 时),程序运行不正常。 Gcalc 获取 ostream(输出文件或 cout)和输入文件或 cin 中的当前行,并将字符串解码为 gcalc 数据上的命令。
#include <ostream>
#include <fstream>
#include <string>
#include <iostream>
#include "Gcalc.h"
using namespace std;
int main(int argc, char* argv[]) {
Gcalc gcalc;
string current_line;
ifstream input;
ofstream output;
if (argc != 1 && argc != 3) {
return 0;
}
if (argc == 3) {
input = ifstream(argv[1]);
cin.rdbuf(input.rdbuf());
output = ofstream(argv[2]);
cout.rdbuf(output.rdbuf());
}
while (cin.good()) {
if (argc == 1) {
cout << "Gcalc> ";
}
getline(cin, current_line);
try {
gcalc.implementCommand(cout, current_line);
}
catch (Quit_Program& error) {
break;
}
catch (std::bad_alloc& error) {
std::cerr << "Error: fatal error - bad allocation" << endl;
break;
}
catch (Exception& error) {
cout << error.what() << endl;
}
}
return 0;
}
istream
是否在读取后没有设置failbit
。 由于 boolean 上下文中的istream
检查badbit
和failbit
并且std::getline
返回您给它的相同istream
,请将您的while (cin.good())
替换为: while(getline(cin, current_line)) { //... only entered if badbit and failbit are false... }
也就是说,通常最好创建一个单独的 function 来读取/写入通用istream
/ ostream
。 这样你就不必弄乱cin
和cout
的rdbuf
了。
#include <fstream>
#include <iostream>
#include <string>
#include "Gcalc.h"
void do_stuff(std::istream& is, std::ostream& os) {
Gcalc gcalc;
std::string current_line;
while(getline(is, current_line)) {
try {
gcalc.implementCommand(os, current_line);
} catch(Quit_Program& error) {
break;
} catch(const std::bad_alloc& error) {
std::cerr << "Error: fatal error - " << error.what() << std::endl;
break;
} catch(Exception& error) {
std::cout << error.what() << std::endl;
// or, if you really want it:
// os << error.what() << std::endl;
}
}
}
int main(int argc, char* argv[]) {
if(argc == 1) {
do_stuff(std::cin, std::cout);
} else if(argc == 3) {
std::ifstream input(argv[1]);
std::ofstream output(argv[2]);
if(input && output) do_stuff(input, output);
}
}
如果你想在程序以交互模式运行时给用户一个提示,你可以添加一个 function 打印提示然后调用std::getline
。 您可以在while
循环中组合它,但它看起来很乱,所以我建议这样:
std::istream& prompt(std::istream& is, std::string& line) {
if(&is == &std::cin) std::cout << "Gcalc> ";
return std::getline(is, line);
}
// ...
while(prompt(is, current_line)) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.