variable file name for fstream
Jan 23, 2011 at 2:42am UTC
How would you go about making it so the user can enter in the name of the file to open? here is my code but it doesn't like line 16.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream DataFile;
string FileNameInput;
string DataFromFile;
cout << "Enter the name of the file you would like to access data from: " << endl;
getline(cin, FileNameInput);
DataFile.open(FileNameInput); //error at this line
if (DataFile.is_open())
{
cout << "File Found." << endl;
cout << "Reading File..." << endl;
cin.get();
while (DataFile.good())
{
DataFile >> DataFromFile;
}
}
else
{
cout << "File not found. Exiting program..." << endl;
return 0;
}
cout << "Printing Data..." << endl;
cout << DataFromFile << endl;
DataFile.close();
return 0;
}
Jan 23, 2011 at 8:11am UTC
fstream::open takes a const char* and you give it an std::string. You can get the const char* to the charachters of the string with the c_str() method. DataFile.open(FileNameInput.c_str());
Jan 23, 2011 at 1:31pm UTC
Oh yeah I fogot about that
Topic archived. No new replies allowed.