|
-
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?
-
April 20th, 2009, 05:14 PM
#2
Re: C++ File IO Question
You need to convert your string object to a char array (cstring) by calling c_str() on your filename object.
Intel Core Duo Macbook w/ Mac OS 10.5.6
gcc 4.2.1 (i386-apple-darwin9.1.0) and Xcode 3.1.1
-
April 20th, 2009, 05:41 PM
#3
Re: C++ File IO Question
So the ifstream class only supports a char type?
-
April 20th, 2009, 05:53 PM
#4
Re: C++ File IO Question
Isn't "filename.txt" a string? Why does this work?
-
April 20th, 2009, 06:00 PM
#5
Re: C++ File IO Question
 Originally Posted by westco
Isn't "filename.txt" a string? Why does this work?
No, "filename.txt" in not a string; it is an array of char primitives. Above when you created a string and assigned it the filename, what is happening is behind the scenes, the string object is converting that array of chars into a string object representation of the same data. Latter, we may need to convert it back, so the c_str() method is provided
Intel Core Duo Macbook w/ Mac OS 10.5.6
gcc 4.2.1 (i386-apple-darwin9.1.0) and Xcode 3.1.1
-
April 20th, 2009, 06:04 PM
#6
Re: C++ File IO Question
 Originally Posted by westco
So the ifstream class only supports a char type?
 Originally Posted by www.cplusplus.com
ifstream ( );
explicit ifstream ( const char * filename, ios_base:: openmode mode = ios_base::in );
It appears so
Intel Core Duo Macbook w/ Mac OS 10.5.6
gcc 4.2.1 (i386-apple-darwin9.1.0) and Xcode 3.1.1
-
April 20th, 2009, 07:48 PM
#7
Re: C++ File IO Question
Thanks Etherous.
I think I understand now.
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
|