0

を求める課題があります

a.) Prompts the user to input the names of 3 files: two input files
and an output file.  
b.) Reads in the two input files line by line and compares the two
lines.
c.) For each line in the inputs, the output should have the line
number, a colon (':'), and either "OK" if the lines match or "DIFF" if
the lines are different.
The input files may be of different lengths. 
- Your program should be case-sensitive, so you do NOT need to worry about converting 

text to lowercase or uppercase.

For example:

input1:
abc
def
g h i

input2:
abc
DEf
ghi
uub

output:
1:OK
2:DIFF
3:DIFF
4:DIFF

基本的に私はコードを書いていますが、パテでこれを実行しようとするたびに、正しくコンパイルされます。

:: a.out
Please enter input file name: abc
terminate called after throwing an instance of 'std::runtime_error'
  what():  Can't open input file: abc
Abort (core dumped)

そのため、ファイル名を入力する前にエラーが返されるので、入力と出力の各セクションを Stroustrup の本に従って書きました。私は正確に何が欠けているのですか、それとも私はこれを間違っていますか? ありがとうございました。

#include "std_lib_facilities_3.h"

int main()
{
    //Input 1
    cout  << "Please enter input file name: ";
    string name;
    cin >> name;
    ifstream ist1(name.c_str());
    if (!ist1) error("Can't open input file: ",name);

    //Input 2
    cout << "Please enter another input file name: ";
    string name2;
    cin >> name2;
    ifstream ist2(name2.c_str());
    if (!ist2) error("Can't open input file name: ",name2);

    //Output
    cout << "Please enter name of output file: ";
    string oname;
    cin >> oname;
    ofstream ost(oname.c_str());
    if (!ost) error("Can't open output file: ",oname);

    string s, t;
    int i = 1;
    int flag = 1;
    while(true) 
    {
        if (!getline(ist1, s)) {flag = 1; break;}
        if (!getline(ist2, t)) {flag = 2; break;}
        ost << i;
        if (s == t)
            ost << ": OK\n";
        else
            ost << ": DIFF\n";
        i++;
    }

    if (flag == 2) {
        ost << i << ": DIFF\n"; 
        i++;
        while (getline(ist1, s)) {ost << i << ": DIFF\n"; i++;}
    }

    if (flag == 1) {
        while (getline(ist2, t)) {ost << i << ": DIFF\n"; i++;}
    }

    return 0;
}
4

1 に答える 1

0

プログラムは問題ありませんが、ファイル拡張子を含むファイル名全体を入力する必要があります。これらのファイルを使用して、プログラムを正常に実行できました。

  • program.cc— プログラムのソース
  • program— あなたのプログラム、コンパイル済み
  • file-a.txt— テキストファイル:

    Hello, world!
    This is a file.
    This line is different.
    But same again.
    
  • file-b.txt— 別のテキスト ファイル:

    Hello, world!
    This is a file.
    This line differs from file A.
    But same again.
    

その後、プログラムを正常に実行できました。

$ ./program
Please enter input file name: file-a.txt
Please enter another input file name: file-b.txt
Please enter name of output file: diffed.txt

この出力で正常に作成されましたdiffed.txt

1: OK
2: OK
3: DIFF
4: OK
于 2012-10-06T19:27:56.937 に答える