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!
Thanks
I will attach the zip folder as well just in case...
entering a string of data to an ofstream file
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 );
The input stream stops at the first blank it encounters.
Try std::getline:
std::getline ( std::cin, filedata );
do i use the getline on the function that is called or when I first get the input from the user?
because when I use it in the main function, getline(cin, filedata), and then run the program i automatically skips that and doesn't let me enter anything.
Use it in the switch/case where you currently do
std::cin >> filedata
Replace that with
std::getline ( std::cin, filedata );
std::cin >> filedata
Replace that with
std::getline ( std::cin, filedata );
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement