![](/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.