Home > Back-end >  How to read file name input by user by function
How to read file name input by user by function

Time:10-09

I try to input a filename to a string, then use ifstream to load the file in the void function. But I call it in another function, it do not load the content of the file. How can I solve this problem?

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

void inputfilename()
{ 
    ifstream file;
    string name;
    getline(cin, name);
    name.append(".txt");
    file.open(name);    
    if ( !file )
    cout << "Error File" << endl;
}

void getColRow(int &row, int &col)
{
    ifstream file;
    inputfilename();
    file >> col;
    file >> row;
    file.close();
}

int main()
{    
    int col, row;
    getColRow(row, col);
    cout << col << ":" << row << endl;

    return 0;
}

CodePudding user response:

The two ifstreams are totally unrelated. You have one called file in inputfilename and another one called file in getColRow.

You can return the stream from the function to use it:

ifstream inputfilename()
{ 
    ifstream file;
    string name;
    getline(cin, name);
    name.append(".txt");
    file.open(name);    
    if ( !file )
    cout << "Error File" << endl;
    return file;
}

void getColRow(int &row, int &col)
{
    ifstream file = inputfilename();
    file >> col;
    file >> row;
    file.close();
}

CodePudding user response:

The ifstream in inputfilename() has nothing to do with the ifstream in getColRow(). The ifstream in getColRow() has no filename assigned to it, so it is not opening the file, and thus has no data to read from.

I would suggest simply having inputfilename() return the filename it read, and let the caller decide what to do with that filename, eg:

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

string inputfilename()
{ 
    string name;
    if ( getline(cin, name) )
        name.append(".txt");
    return name;
}

void getColRow(int &row, int &col)
{
    ifstream file(inputfilename());
    if ( !file.is_open() ) {
        cout << "Error Opening File" << endl;
        col = row = -1;
    }
    else if ( !(file >> col >> row) ) {
        cout << "Error Reading File" << endl;
        col = row = -1;
    }
}

int main()
{    
    int col, row;
    getColRow(row, col);
    cout << col << ":" << row << endl;

    return 0;
}
  •  Tags:  
  • c
  • Related