Sign in to follow this  
wayneprim

entering a string of data to an ofstream file

Recommended Posts

wayneprim    148
I am trying to create a program that allows the user to do 2 things (create a new file in the current directory, or search a file and display the word count) The word count works fine but when I try to allow the user to create a file it starts going wrong. I first ask the user to input a filename, and then enter some initial data into a string variable. That string variable gets passed to the createFile() function which takes care of entering the data into the file.

When I run this program I enter the file data I wish to put in the created file, say for example " Hello File Data" and when I look into that file once its been created there is only the first word ("Hello") in the case of this example. Here is the code:

The main function:

[source lang="cpp"]

cout << "Enter the file name: " << endl;
cin >> filename;
outFile.open(filename.c_str());//create the file

if (!outFile)
{
//file could not be created
cout<< "File could not be completed" << endl;
break;

}
else // file was created
cout << "FILE WAS COMPLETED NAMED: " << filename << endl;;

//ask the user to put some data y/n
cout << "Would you like to set some initial data in the file? y/n" << endl;
cin >> choice;
switch(choice)
{
case 'y':
cout << "Enter the data: " << endl;

cin >> filedata;
user1.createFile(outFile, filedata);
break;
case 'n':
cout << "Ok then dont create initial data... Your created file is blank" << endl;
break;
}



[/source]

The create filefunction:
[source lang="cpp"]
void User::createFile(ofstream &outfile, string filedata)
{
//output the file into outfile
outfile << filedata;

cout << "You have successfully saved the data you entered" << endl;


}
[/source]

Please help! [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Thanks

I will attach the zip folder as well just in case...

Share this post


Link to post
Share on other sites
Endurion    5407
Beside your zip packing (unnamed .zip in another zip) the problem is that you're using the input stream >> operator.
The input stream stops at the first blank it encounters.

Try std::getline:

std::getline ( std::cin, filedata );

Share this post


Link to post
Share on other sites
wayneprim    148
Thanks, but now when I change cin>> to getline() the program doesn't let me enter the data. Instead it just skips the data and jumps to your data has been entered successfully... Is there anyway to make the program "pause" to allow me to enter the data?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this