0

コマンドラインで指定された複数のファイルを開くプログラムを書いています。私は最初に配列表記でそれを行いました。それはうまくいくようです。現在、私は練習のためにコンパクトなポインター表記法を使用してポインターに慣れようとしていますが、正しく行っていません。誰かが私が間違っていることを教えてくれますか? ありがとう。

#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;

ifstream *OpenFiles(char * const fileNames[], size_t count)
{   
    ifstream *fileObj = new ifstream[count];

    if (fileObj == NULL) {
        cerr << "Failed to create space for files";
        exit(EXIT_FAILURE); 
    }

//  working loop with array notation
//  for (int loopCount = 0; loopCount < (int) count; loopCount++) {
//      fileObj[loopCount].open(fileNames[loopCount], ios::out);
//      if (fileObj[loopCount].is_open()) {
//          cout << "Opened " << fileNames[loopCount] << "\n";  
//      }
//
//  }

// start compact pointer notation that doesn't work
    ifstream *start, *end;

    for (start = fileObj; start < end; start++) {
        start.open(fileNames, ios::out);
        if (start.is_open()) {
            cout << "Opened " << start << "\n";
        }
    }
    return fileObj;
}
4

2 に答える 2

1

endは初期化されていないため、start < endtrue/false はスタックに残されたランダム データに依存します。end を次のように初期化する必要があります。

end = fileObj + count;
于 2010-03-04T06:32:39.570 に答える
0

ポインターを逆参照するか、ドットの代わりに矢印を使用する必要があります。さらに、開きたいファイル名を選択する必要があります。

ifstream *end = fileObj + count;
for (ifstream *start = fileObj; start < end; start++) {
    start->open(fileNames[start-fileObj], ios::out);
    if (start->is_open()) {
        cout << "Opened " << fileNames[start-fileObj] << "\n";
    }
}
return fileObj;

私の意見では、この場合は配列表記を使用することをお勧めします。

于 2010-03-04T06:41:35.453 に答える