|
-
April 20th, 2009, 05:12 PM
#1
C++ File IO Question
The code below attempts to read in a file. It first asks the user to enter the name of the file.
Here is the code:
#include <iostream>
#include <string>
#include <vector>
#include <fstream> //file io support
#include <cstdlib> //exit() support
int main(void)
{
using namespace std;
string data_in = "";
string filename = "";
cout << "Enter filename: ";
getline(cin,filename);
ifstream file_in (filename); //create input file type
if(file_in.is_open()) //if the file does not open properly
{
while(! file_in.eof())
{
getline(file_in,data_in);
cout << endl << data_in;
}
file_in.close();
}
else
{
cout << "Unable to open file";
}
return 0;
}
The problem I am having is the compiler is complaining about the following line:
ifstream file_in (filename);
If I replace this line with the following, all is well:
ifstream file_in ("filename.txt");
Why is this? Why can't I use a variable name here? How can I get this to work?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|