-1

So, I was just starting C++, and I have a problem. I declared a string variable and all that, but when I have input give the variable a value, then try to display it, it only shows the first word of the sentence.

#include <iostream>
#include <string>

using namespace std;
using std::string;

int main()
{
        string answer;
        cout << "Give me a sentence and I will repeat it!";
        cin >> answer;
        cout << answer;
        return 0;
}

For example, I entered "Yay it worked!", and it outputted "Yay"

Number1son100
  • 219
  • 2
  • 12

2 Answers2

3

The delimiter for std::cin is whitespace, so it only took the first word of your sentence. Like @πάνταῥεῖ said, use std::getline(cin,answer) instead.

1

As the comment explains, cin will only read until the first bit of whitespace is met (in your case this seems to be a space). Instead, you can use std::getline, which will read until a specified character, or a return by default:

std::string answer;
std::cout << "Give me a sentence and I will repeat it!";
std::getline(std::cin, answer):
std::cout << answer;

To make it read until a specified character would look like:

char end_char = 'a';
std::getline(std::cin, answer, end_char);
scohe001
  • 15,110
  • 2
  • 31
  • 51