How to read a complete line from the user using cin?
The code cin >> y;
only reads in one word, not the whole line. To get a line, use:
string response;
getline(cin, response);
Then response
will contain the contents of the entire line.
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
int main()
{
char write_to_file;
std::cout << "Would you like to write to a file?" << std::endl;
std::cin >> write_to_file;
std::cin >> std::ws;
if (write_to_file == 'y' || write_to_file == 'Y')
{
std::string str;
std::cout << "What would you like to write." << std::endl;
std::getline(std::cin, str);
std::ofstream file;
file.open("Characters.txt");
file << str.size() << " Characters." << std::endl;
file << std::endl;
file << str;
file.close();
std::cout << "Done. \a" << std::endl;
}
else
std::cout << "K, Bye." << std::endl;
}
string str;
getline(cin, str);
cin >> ws;
You can use getline function to read the whole line instead of reading word by word. And The cin>>ws is there to skip white spaces. And you find some detail about it here : http://en.cppreference.com/w/cpp/io/manip/ws