标准C++中的字符串输入

String input in standard C++

本文关键字:字符串 输入 C++ 标准      更新时间:2023-10-16

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

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

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

...
cout << "Enter the employee Idn";
cin >> empid;
cin.ignore();
cout << "Enter the Employee's namen";
...
cin>>empid

回车符留在输入流中,然后在调用 cin.getline 方法后立即拾取该回车符,因此它会立即退出。

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

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