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;
}
You can use std::getline to read an entire line from user input:
std::string text;
std::getline(std::cin, text);
Live demo
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With