【问题标题】:String input in standard C++ [duplicate]标准 C++ 中的字符串输入 [重复]
【发布时间】:2016-05-01 17:48:23
【问题描述】:

我想在这个 C++ 程序中输入字符串,但是下面的代码不起作用。它不会将员工的姓名作为输入。它只是跳过。抱歉,我是 C++ 新手。

#include<iostream>
#include<string>
using namespace std;
int main()
{
  int empid;
  char name[50];
  float sal;
  cout<<"Enter the employee Id\n";
  cin>>empid;
  cout<<"Enter the Employee's name\n";
  cin.getline(name,50);
  cout<<"Enter the salary\n";
  cin>>sal;
  cout<<"Employee Details:"<<endl;
  cout<<"ID : "<<empid<<endl;
  cout<<"Name : "<<name<<endl;
  cout<<"Salary : "<<sal;
  return 0;
}

【问题讨论】:

  • std::getline。但是将std::cin &gt;&gt; foogetline 的任何一种形式混合使用是很棘手的,最好避免,因为它们以不同的方式处理换行符,并且相互混淆。我发现最好一次读取一行,然后在程序中处理每一行。
  • 感谢您的回答。你能告诉我为什么 cin.getline() 语法不起作用吗?
  • std::cin.getline() 要求您自己管理缓冲区,这总是比较棘手。例如,如果您的用户有一个长名称怎么办? std::string name; std::getline(std::cin, name); 为您处理此问题。至于为什么您当前的版本不起作用:cin&gt;&gt;empid 在流中留下一个尾随的 \n 字符,getline 在看到名称之前看到 before。所以你阅读了上一行的结尾,而不是你真正想要的那一行。不要混合两种阅读方式,这是一个 PITA。

标签: c++ string


【解决方案1】:

您需要跳过在以下行执行后留在输入缓冲区中的\n 字符:cin &gt;&gt; empid;。要删除此字符,您需要在该行之后添加 cin.ignore()

...
cout << "Enter the employee Id\n";
cin >> empid;
cin.ignore();
cout << "Enter the Employee's name\n";
...

【讨论】:

    【解决方案2】:

    cin&gt;&gt;empid 将回车留在输入流中,然后在调用cin.getline 方法后立即将其拾取,因此它会立即退出。

    如果您在 getline 之前读取了一个字符,则您的代码可以正常工作,尽管这可能不是解决问题的最佳方法 :)

    cout<<"Enter the employee Id\n";
    cin>>empid;
    cout<<"Enter the Employee's name\n";
    cin.get();
    cin.getline(name,50);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-04
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      相关资源
      最近更新 更多