标准C+中的字符串输入+; 我想用字符串输入这个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; int main() { int empid; 字符名[50]; 浮球; 香豆素; cout

标准C+中的字符串输入+; 我想用字符串输入这个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; int main() { int empid; 字符名[50]; 浮球; 香豆素; cout,c++,string,C++,String,您需要跳过执行以下行后留在输入缓冲区中的\n字符:cin>>empid;。要删除此字符,您需要在该行之后添加cin.ignore() ... cout << "Enter the employee Id\n"; cin >> empid; cin.ignore(); cout << "Enter the Employee's name\n"; ... 。。。 cout>empid; cin.ignore(); coutempid将退出输入流中的回车符,然后在

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

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

coutempid将退出输入流中的回车符,然后在调用
cin.getline
方法后立即提取该回车符,因此它将立即退出

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

coutempid;

当然可以。但是将
std::cin>>foo
getline
的任何一种形式混合使用都是很棘手的,而且最好避免,因为它们对待换行符的方式不同,并且相互混淆。我发现最好一次读一行,然后在程序中处理每一行。谢谢你的回答。你能告诉我为什么cin.getline()语法不起作用?
std::cin.getline()
要求您自己管理一个缓冲区,这总是比较棘手。例如,如果您的用户有一个长名称,该怎么办?
std::string name;std::getline(std::cin,name);
为您处理此问题。至于当前版本不起作用的原因:
cin>>empid
在流上留下一个尾随字符
\n
,它在看到名称之前先看到。因此,您读取前一行的末尾,而不是实际需要的行。不要混合使用这两种读取方式,这是PITA。
cout<<"Enter the employee Id\n";
cin>>empid;
cout<<"Enter the Employee's name\n";
cin.get();
cin.getline(name,50);