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 < end真/假取决于堆栈上留下的随机数据。您应该使用以下命令初始化 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 回答