什么导致关于字符串的错误?

时间:2014-03-27 07:33:23

标签: c++ 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;
}

我的控制台输入/输出如下所示:

  

你叫什么名字?
  John Titor
  你好约翰!
  请给我两个以空格分隔的数字
  总和0 + 1961462997是1961462997

它不打印全名,只打印“John”,它甚至不会问我放两个数字。

1 个答案:

答案 0 :(得分:7)

您应该使用std::getline来获取带空格的字符串。 std::cin用空格分隔字符串。

getline(cin, name);

此外,您可以在std::string之前std::cout打印.c_str()

cout << name;
相关问题