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