How to read a complete line from the user using cin?

FuzionSki picture FuzionSki · Mar 28, 2011 · Viewed 77.4k times · Source

Here is my current C++ code. I would like to know how to write a line of code. Would I still use cin.getline(y) or something different? I've checked, but can't find anything. When I run it, it works perfectly except it only types one word instead of the full lines I need it to output. This is what I need help with. I've outlined it in the code.

Thanks for helping

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{
    char x;

    cout << "Would you like to write to a file?" << endl;
    cin >> x;
    if (x == 'y' || x == 'Y')
    {
        char y[3000];
        cout << "What would you like to write." << endl;
        cin >> y;
        ofstream file;
        file.open("Characters.txt");
        file << strlen(y) << " Characters." << endl;
        file << endl;
        file << y; // <-- HERE How do i write the full line instead of one word

        file.close();


        cout << "Done. \a" << endl;
    }
    else
    {
        cout << "K, Bye." << endl;
    }
}

Answer

ybakos picture ybakos · Oct 4, 2011

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.