Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store paragraph of text in variable C++

Tags:

c++

I am trying to write a program that takes user's input and stores the entire paragraph in a variable. However, if the user enters: "Hello, this is some text." It only returns "Hello" Can anyone help?

Thanks!

#include <iostream>
#include <iomanip>

using namespace std;

class GetText
{
public:

    string text;

    void userText()
    {
        cout << "Please type a message: ";
        cin >> text;
    }

    void to_string()
    {
        cout << "\n" << "User's Text: " << "\n" << text << endl;
    }
};

int main() {

    GetText test;
    test.userText();
    test.to_string();

    return 0;
}
like image 362
ChaseHardin Avatar asked Dec 21 '25 23:12

ChaseHardin


2 Answers

You can use std::getline to read an entire line from user input:

std::string text;
std::getline(std::cin, text);

Live demo

like image 118
Shoe Avatar answered Dec 23 '25 13:12

Shoe


When getting values using cin, the input stream treats spaces as a string split delimiter by default. Instead, you should use std::getline(), which reads the input until it detects a new line character.

However, like I said above, std::getline() reads the input until it detects a new line character, meaning that it can only read one line at a time. So in order to read an entire paragraph with multiple lines, you'll need to use a loop.

#include <iostream>
#include <iomanip>
#include <string> //For getline()

using namespace std;

// Creating class
class GetText
{
public:

    string text;
    string line; //Using this as a buffer

    void userText()
    {
        cout << "Please type a message: ";

        do
        {
            getline(cin, line);
            text += line;
        }
        while(line != "");
    }

    void to_string()
    {
        cout << "\n" << "User's Text: " << "\n" << text << endl;
    }
     };

     int main() {

    GetText test;
    test.userText();
    test.to_string();
    system("pause");
    return 0;
}

This code reads the stream line by line, storing the current line in the string variable "line". I use the variable "line" as a buffer between the input stream and the variable "text", which I store the entire paragraph in using the += operator. It reads the input until the current line is an empty line.

like image 36
Baki Avatar answered Dec 23 '25 14:12

Baki