yagamilight1994
yagamilight1994

Reputation: 15

What is causing this error about string?

#include <iostream>
#include <string>

int main(void)
{
  using std::cout;
  using std::cin;
  using std::string;

  string name;
  int n1, n2;

  cout << "What is your name ?\n";
  cin >> name;
  cout << "Hello " << name.c_str() <<"!\n"
       << "Please give me two number separated by space\n";
  cin >> n1 >> n2;
  cout << "Sum of " << n1 << " + " << n2 << " is " << n1 + n2 << "\n";

  return 0;
}

My console input/output looks like this:

What is your name ?
John Titor
Hello John!
Please give me two number separated by space
Sum of 0 + 1961462997 is 1961462997

It doesn't print the full name, only "John", and it doesn't even ask me about puting two numbers.

Upvotes: 1

Views: 102

Answers (1)

masoud
masoud

Reputation: 56479

You should use std::getline to get a string with spaces. std::cin separates the strings by spaces.

getline(cin, name);

In addition, you can print a std::string by std::cout without .c_str():

cout << name;

Upvotes: 7

Related Questions