无法从用户输入打开文件

时间:2018-04-07 19:43:31

标签: c++ file

我尝试使用与源代码位于同一目录中的相对名称,从用户输入中打开C ++文件。但是,它一直让我失败,我无法弄清楚原因。

编辑:我忘了C ++使用双反斜杠来读取路径,完全合格的文件名工作!我仍然需要相对位置才能工作:/

这是我的代码:

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

bool openFileIn(fstream& file, string name)
{
    file.open(name, ios::in); 

    if (file.fail())
        return false;
    else
        return true;
}

int main()
{
    int size = 0;
    fstream inFile;
    string fileName;

    // Get filename from user
    cout << "Please input the stock data file name: ";
    getline(cin, fileName);

    // Open and check for errors
    if (!openFileIn(inFile, fileName))
    {
        cerr << "Error opening file for input!" << endl;
        exit(EXIT_FAILURE);
    }

0 个答案:

没有答案