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

标签 c++ string

<分区>

我想将字符串输入此 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;
}

最佳答案

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

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

关于c++ - 标准 C++ 中的字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34992254/

相关文章:

string - 在 Swift 中使用变量选择元组索引

c++ - 使 std::to_string 使用 void 指针,如 operator<<?

c++ - 是否可以在 C++ 中的 switch 范围之外声明变量?

c++ - 如何从 uint8_t 数组中提取不同大小的值?

c++ - 常规转换的内存损坏?调用了错误的函数

javascript - 在给定字符串中找到最佳子串集

javascript - 删除字符串中所有出现的文本

c - 随机字符数组排序

c++ - Windows 上的微秒分辨率时间戳

c++ - 假设有一个名为A的类,传递下面两个对象有什么区别: (a) A obj1 and (b) A obj1()?