By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,900 Members | 1,232 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,900 IT Pros & Developers. It's quick & easy.

Opening files

P: n/a
The following does not work when opening a file that contains a space
in the name. It works perfectly on files that have no space in the
name. Any ideas on how to make this work? Surely I shouldn't have to
manually change the file names first.
char hand[30];
cout<<"enter file name: ";
cin>>hand;
ifstream myfile (hand);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();

Any help would be appreciated.

Nov 3 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
arganx wrote:
The following does not work when opening a file that contains a space
in the name. It works perfectly on files that have no space in the
name. Any ideas on how to make this work? Surely I shouldn't have to
manually change the file names first.
char hand[30];
cout<<"enter file name: ";
cin>>hand;
ifstream myfile (hand);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();

Any help would be appreciated.


It doesn't work because std::cin stops at the first whitespace
character. You could use getline to get a string with spaces, and you
should prefer std::string to arrays of characters:

string hand;
cout << "enter file name: " << flush;
getline( cin, hand );
ifstream myfile( hand.c_str() );
string line;
while( getline( myfile, line ) ) // Note: checks eof and other
failures
{
cout << line << endl;
}
// Note: the destructor will close the file automatically

Cheers! --M

Nov 3 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.