Lỗi nhập information trong mảng struct

#include <iostream>
#include <string.h>
using namespace std;
struct students_infor
{
	int stcode;
	char fullname[10];
	int dayofbirth;
	double averagescore;
};

void Input (students_infor &hs)
{
	cout<<"Input student code: "; cin>>hs.stcode;cout<<endl;
	fflush(stdin);
	cout<<"Input fullname: "; gets(hs.fullname); cout<<endl;
	cout<<"Input day of birth: "; cin>>hs.dayofbirth;cout<<endl;
	cout<<"Input average score: "; cin>>hs.averagescore; cout<<endl;
	//cout<<"================================="<<endl;
}

void Output (students_infor hs)
{
	cout<<"student code: "<<hs.stcode<<endl;
	cout<<"full name: ";puts (hs.fullname); cout<<endl;
	cout<<"Day of birth: "<<hs.dayofbirth<<endl;
	cout<<"Average score: "<<hs.averagescore<<endl<<endl;
	//cout<<"================================="<<endl;
}

void InputArr_structInfor (students_infor Arr[100], int &n)
{
	//cout<<"Input n: "; cin>>n;
	for (int i=0; i<n; i++)
	{
		Input (Arr[i]);
	}
}

void OutputArr_structInfor (students_infor Arr[100], int n)
{
	for (int i=0; i<n; i++)
	{
		Output (Arr[i]);
	}
}

int main()
{
	students_infor Arr[100];
	int n=2;
	InputArr_structInfor (Arr,n);
	OutputArr_structInfor(Arr,n);
	
} 

Khi em nhập student code có số thì nó đúng như vậy image

Nhưng khi em nhập student code chỉ có chữ mà không có số thì nó lại bị như vậy image

Làm sao đễ fix ạ?

Sửa cin >> hs.stcode thành:

    if (cin >> hs.stcode) {
        cin.clear();
        cin.ignore(1000, '\n');
    }

Hoặc đơn giản hơn là đổi stcode thành char* . :slight_smile:

2 Likes

Mã ID là char[] nhóe :slight_smile: tùy yêu cầu char[] bao nhiêu thôi.

5 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?