【问题标题】:never get the opportunity to enter a string input. C++ [duplicate]永远没有机会输入字符串输入。 C++ [重复]
【发布时间】:2014-11-17 04:23:29
【问题描述】:

我正在尝试从用户那里读取两个字符串并输出它们。 如果我在第一个输入中输入“Micheal Jordan”,程序不会给我机会输入我的第二个字符串。

#include "iostream"
#include "cstring"

int main()
{
  using namespace std;
  string name;
  string dessert;

  cout << "Enter your name: \n";
  cin >> name;

  cout << "Enter your favorite dessert: \n";
  cin >> dessert;

  cout << "I have some delicious " << dessert << " for you, " << name << "." << endl;

  return 0;
}

输出:

./a.out 
Enter your name: 
Micheal Jordan
Enter your favorite dessert: 
I have some delicious Jordan for you, Micheal.

如果我输入不带空格的名称,则代码可以正常工作。

./a.out 
Enter your name: 
MichealJordan
Enter your favorite dessert: 
Cake
I have some delicious Cake for you, MichealJordan.

所以我猜这是造成这个问题的空间,你们能告诉我如何解决它吗?我也想知道这个空间发生了什么。 谢谢!

【问题讨论】:

标签: c++ string input output


【解决方案1】:

std::getline(cin, name);获取输入直到行尾;

如果你仍然有同样的问题,你可以让用户输入名字然后输入姓氏,但希望 getline 能工作:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多