如何告诉你的程序你想要读哪个文件C ++

时间:2015-02-05 02:59:55

标签: c++

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void read();

int main() {
   read();
   return 0;
}




void read () {
   string file("");
   string nameOfFile("");
   cin >> nameOfFile;
   ifstream in (nameOfFile);
   while ( !in.eof() ) {
    getline(in, file);
    cout << file;
    cout << endl;
}
cout << file;
in.close();
}

为什么这不起作用,我正试图这样做,所以我可以输入我想要阅读的文件?

我是C ++的新手,对不起,如果这是一个明显的解决方法。

3 个答案:

答案 0 :(得分:1)

你必须改变

ifstream in (nameOfFile);

ifstream in (nameOfFile.c_str());

因为ifstream的默认构造函数不接受std::string作为参数,所以它需要char *。因此,使用函数std::string::c_str()std::string转换为char *

答案 1 :(得分:0)

一点反馈:

void read () {
   string file("");        // you don't need the ("") bit; empty by default,
                           //   and "file" is a terrible choice of identifier as
                           //   it sounds more like an ifstream than a string
                           //   used to hold one line from the file.
                           //   I tend to use "string line;" for this.
   string nameOfFile("");  // ditto
   cin >> nameOfFile;      // you should test for success of input, like this:
                           //   if (!cin >> nameOfFile) {
                           //       std::cerr << "error reading filename from stdin\n";
                           //       exit(1);
                           //   }
   ifstream in (nameOfFile); // test for success getting file open like this:
                             // if (ifstream in(nameofFile))
                             // {
   while ( !in.eof() ) {     // NEVER check eof before attempting input, instead:
    getline(in, file);       //     while (getline(in, file))
    cout << file;            //         cout << file << endl; // can "chain"
    cout << endl;            // }
                             // else
                             //     std::cerr << "couldn't open " << nameOfFile
                             //         << '\n';
}                            // no need for extra cout nor explicit close, as
cout << file;                // the ifstream destructor closes anyway.
in.close();
}

答案 2 :(得分:-1)

您需要使用in.open()打开iostream,并处理文件不存在的情况。这是功能:

void read() {
    string file("");
    string fileContent = "";
    string nameOfFile("");
    cin >> nameOfFile;
    ifstream in(nameOfFile.c_str());
    in.open(nameOfFile, ios::in);
    if (in){
        while (!in.eof()) {
            getline(in, file);
            fileContent += file;
        }
        cout << fileContent;
        in.close();
    }
    else {
        cout << "Could not open file.";
    }
}