Có bài toán nhập sv yêu cầu kiểm tra code, name,grade.
Bài của em code phần kiểm tra dữ liệu ko biết sai ở đâu, bác bào soi code chỉ giúp nha.
Ví dụ em nhập code là BH12345 với name là kaka, thì code in ra sẽ là BH12345kaka chứ không phải BH12345, mà name vẫn in đúng.
Bác nào kíu với :((
Hàm student.cpp
Code:
#include <iostream>
#include "student.h";
using namespace std;
#include <iomanip>
Student::Student()
{
strcpy(code,"");
strcpy(name,"");
grade = 0;
}
Student::Student(char* n_code, char* n_name, double n_grade)
{
strcpy(code,n_code);
strcpy(name,n_name);
grade = n_grade;
}
void Student::set()
{
bool checkCode=true;
do
{
cout<<"Enter code: ";
fflush(stdin);
cin>>code;
if(strlen(code)<7 || strlen(code) >7)
{
cout<<"Lenght must be 7. Try again"<<endl;
cin.clear();
cin.ignore(2000, '\n');}
else if(code[0]<'A' || code[0]>'Z' ||code[1]<'A' || code[1]>'Z'){
cerr<<"Invalid input,try again."<<endl;
cin.clear();
cin.ignore(2000, '\n');}
else checkCode=false;
}while(checkCode);
bool checkName=true;
do
{
cout <<"Enter name: ";
fflush(stdin);
cin>>name;
if(strlen(name)>30)
{
cout<<"Lenght must lower than 30. Try again"<<endl;
cin.clear();
cin.ignore(2000, '\n');}
else checkName=false;
}while(checkName);
bool checkGrade = true;
while (checkGrade)
{
cout << "Enter grade: ";
cin >> grade;
if(cin.fail())
{
cout << "Invalid input.Try again." << endl;
cin.clear();
cin.ignore(2000, '\n');
}
else
{
if (char (cin.get() !='\n'))
{
cout << "Invalid input.Try again." << endl;
cin.ignore(2000,'\n');
}
else if (grade < 0 || grade >10)
{
cout <<"Grade is must higher than 0 and lower than 10 " << endl;
}
else checkGrade = false;
}
}
}
void Student::display()
{
cout <<setw(15)<< left << code;
cout <<setw(30)<< left << name;
cout <<setw(10)<< left << grade;
cout << endl;
}
void Student::search(Student s[],int n)
{
int count=0;
cout<<"Enter Code of student who you want to search: ";
cin.getline(find,7);
for(int i=0;i<n;i++)
{
if(strcmp(s[i].code,find)==0)
{
cout<<"Student who you want to search is: "<<s[i].name<<endl;
count++;
}
}
if(count==0)
cout<<"Can not find student has this code."<<endl;
}
Hàm main.cpp
Code:
#include <iostream>
#include "student.h";
using namespace std;
#include <iomanip>
int main() {
Student s[50];
int n;
cout<<"Enter number of student you want to add: ";
cin >> n;
for(int i=0; i<n; i++)
{
cout<<endl<<"Student: "<<i+1<<endl;
s[i].set();
}
cout << endl;
cout <<"Information of all Student."<<endl;
cout << endl;
cout <<setw(15)<<left<<"Code";
cout <<setw(30)<< left <<"Name";
cout <<setw(10)<< left <<"Grade";
cout << endl;
for(int i=0; i<n; i++)
{
s[i].display();
}
Student a;
a.search( s, n);
system("pause");
return 0;
}
Hàm student.h
Code:
class Student{
public:
char code[7];
char name[30];
double grade;
char find[7];
public:
void display();
void search(Student s[],int n);
void set();
Student();
Student(char* n_code, char* n_name, double n_grade);
};