1
#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.

1
  • 6
    Use the getline() function to get the full input. std::cin reads strings word by word. Commented Mar 27, 2014 at 7:35

1 Answer 1

7

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;
Sign up to request clarification or add additional context in comments.

3 Comments

The getline function really works, thanks. But, I've found another input method, if I input like this : string name = "John Titor"; It will prints the full name, if we use cout. What is the difference between this method with the method before? Because I think, both method will save the value "John Titor" into name, but why the print out different?
@M M, oh wait a minute, Did you want to say the "cin" method save value "John Titor" as "John" into name? If that so, why the part of "Input two numbers" didn't run well? Or Maybe, the value "Titor" will be the value of n1? if that so, why it didn't ask the other n2 value?
@yagamilight1994: Yes, exactly. and again Yes. For your third question, I think because when cin fails to fit a string into a int it stops reading more and you need to reset the stream. So, just use getline and avoid that weird behaviors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.