I'm trying to output a string to a basic .txt file. And it only partially works, and by that I mean that it only accepts the first word of whatever I type. I need to be able to have no character limit as well (the user can type in however much they want)
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in_stream;
ofstream out_stream;
in_stream.open("advice.txt");
if (in_stream.fail())
{
cout << "input file opening failed.\n";
exit(1);
}
char next;
in_stream.get(next);
while (! in_stream.eof())
{
cout << next;
in_stream.get(next);
}
out_stream.open("advice.txt", ios::app); //Append data to file
if (out_stream.fail())
{
cout << "output file opening failed.\n";
exit(1);
}
//Output text into the file (Problem is in here)
string mystring;
cin >> mystring, "\n\n";
out_stream << " - " << mystring << "\n\n";
in_stream.close();
out_stream.close();
cin.get();
cin.get();
return 0;
}
Any future help will be greatly appreciated :) Thanks in advance!
The extraction operator truncates on whitespaces. Use std::getline() to read the entire line.
Instead of:
cin >> mystring, "\n\n";
Make it:
std::getline( std::cin, mystring );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.