解决C++在输入字符串时多输入字符导致输入流覆盖接下来的输入
在需要丢弃的输入流处加入一下代码
cin.ignore();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
需要在头文件中导入
#include<limits>
#include <iostream>
#include <limits>
#include <cstring>
using namespace std;
struct student{
int age;
char name[10];
string school;
};
int main()
{ student stu;
student *p=new student;
//enter value
cout<<"before enter the sizeof is :"<<sizeof stu<<endl;
cout<<"enter stu age: ";
cin>>stu.age;
cin.get(); //回车符
cout<<"enteer stu name: ";
cin.get(stu.name,10);
cin.ignore();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"enter stu school: ";
getline(cin,stu.school);
cout<<"after enter the sizeof is :"<<sizeof stu<<endl;
//指针
p=&stu;
cout<<p->age<<" "<<p->name<<" "<<p->school<<endl;
cout<<stu.age<<" "<<stu.name<<" "<<stu.school<<endl;
return 0;
}
注意 在linux系统下中文字符默认是占用三个字符的。
我的资源中有c++相关辅导书籍