标准C++中的字符串输入
String input in standard C++
我想在这个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);
相关文章:
- 如何使用堆栈将字符串输入拉伸 k 次
- 不确定出了什么问题(字符串输入)
- 如何获取字符串输入n次?
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- isPalindrome不显示输出,isPalindrome函数未使用字符串输入作为字符串参数进行测试
- C++ 对象数组字符串输入在控制台上不起作用
- 为什么 cin 在包含字符串标头后接受字符串输入
- 拆分字符串输入并查找字符是否有效
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 将字符串输入到多维数组中
- 字符串输入后的空格
- 字符串流中的自定义字符串输入
- C 未验证字符串输入
- 总结数字字符串输入的最佳方法
- 如何验证用户将字符串输入到std :: cin中
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 如何在C++中检测字符串输入中的换行符
- C++将字符串输入拆分为两个整数
- 如何检查字符串输入是否为有效的双精度
- 在读取数据文件时,如何找到用户字符串输入的字谜?