我寫了應該打開兩個文本文件(prog2a.dat和prog2b.dat)C++程序一個C++程序,可以在命令行中的Linux合併文件和文件寫的內容指定範圍的行到輸出文件(outfile.dat)。我寫了一個基於我們給出的例子的程序(從第一個文件中取第5-15
行,第二個文件取第4-12
行並將它們合併到輸出文件中)完美地工作。但是,在請教授對作業的另一部分進行了一些澄清之後,我發現我沒有正確地做到這一點。我編寫了代碼,以便它將始終輸出前面提到的行的範圍,但程序實際上應該允許用戶通過鍵入以下命令,使用任意範圍合併命令行中的文件:寫作
prog2 in1 5-15 in2 4-12 outfile
但我不知道如何調整我的當前程序,以允許這樣做。
下面是我寫的代碼,請記住,這適用於寫入方式,但不適用於命令行應如何工作(希望有意義):
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
// Create output file
std::ofstream outFile("outfile.dat", ios::out);
// Open input file 1, if can't be opened, exit
ifstream in1;
in1.open("prog2a.dat");
std::string line;
int count = 1;
if (!in1) {
cerr << "Open Failure" << endl;
exit(1);
} // end if
else {
while (std::getline(in1, line)) {
if (count >= 5 && count <= 15) {
outFile << line << "\n"; /*writes the contents of
lines 5-15 to outfile.dat*/
}
++count;
} // end while
} // end else
in1.close(); // close in1 (prog2a.dat)
outFile << "\n"; // add a blank line after the output from prog2a.dat
count = 1; // reset the line count to 1 before opening next file.
// Open input file 2, if can't be opened, exit
ifstream in2;
in2.open("prog2b.dat");
if (!in2) {
cerr << "Open Failure" << endl;
exit(1);
} // end if
else {
while (std::getline(in2, line)) {
if (count >= 4 && count <= 12) {
outFile << line << "\n"; /*writes the contents of the
lines 4-12 to outfile*/
}
++count;
} // end while
} // end else
in2.close(); // close in2 (prog2b.dat)
} // end main
是否有任何簡單的方法來使這項工作,我所描述的使用命令行?另外,我應該把它分成三個文件,頭文件,程序文件和測試文件(測試文件包含main()
,並且應該關閉3個打開的文件並顯示任何錯誤消息),但是我得到真的很困惑,應該在頭文件中進行什麼。我知道頭文件應該包含類定義和構造函數,但是不知道如何爲這個特定的程序做這些工作?我非常新,所以任何指針將不勝感激。
這個程序真的編譯? '(class prog2 {int main()..})'? – Amadeus 2014-09-23 02:34:00
是的,並在輸出文件中生成正確的輸出。 – 2014-09-23 02:34:43
你不能在類中使用main(),這不是java。你的程序不能編譯,只需複製/粘貼它,然後用g ++進行嘗試。 – vsoftco 2014-09-23 02:47:18