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

3

我想在这个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 >> foo与任一形式的getline混合使用是棘手的,最好避免,因为它们对换行符的处理方式不同,并且会相互混淆。我发现最好逐行读取,然后在程序内处理每一行。 - BoBTFish
谢谢你的回答。你能告诉我为什么cin.getline()语法不起作用吗? - user4570754
4
std::cin.getline()需要你自己管理缓冲区,这通常比较棘手。例如,如果用户输入一个很长的名字会怎么样呢?而std::string name; std::getline(std::cin, name);则为你处理了这个问题。至于为什么你当前的版本不起作用:cin>>empid在流中留下了一个尾随的\n字符,而getline在读取名字之前就看到了它。因此你读到的是上一行的结尾,而不是你实际想要的那一行。不要混合两种方法来读取,这非常麻烦。 - BoBTFish
2个回答

4

在执行以下代码后,您需要跳过输入缓冲区中剩余的\n字符:cin >> empid;。为了删除此字符,您需要在该行之后添加cin.ignore()

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

2
cin>>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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接