Opening files

A

arganx

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.
 
M

mlimber

arganx said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top