Về gets() và cin.getline()

Tại sao thầy em lại nói là không nên sử dụng gets() nhiều vậy ạ? Thay vào đó là nên sử dụng cin.getline(). Tính hỏi thì thầy thì thầy lơ đi mất tiêu.
Ai giải thích giúp e, em cảm ơn nhiều ạ.

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
struct sinhvien
{
	
	char hoten[51];
	float diemtin,diemnn,dtb;
	char xeploai[10];
};
void nhapdssv(sinhvien dssv[],int &n)
{
	cin>>n;
	for(int i=0;i<n;i++)
	{
		fflush(stdin);
		
		gets(dssv[i].hoten);
		cin>>dssv[i].diemtin>>dssv[i].diemnn;
		dssv[i].dtb=(dssv[i].diemtin+dssv[i].diemnn)/2;
		if(dssv[i].dtb<4)
		strcpy(dssv[i].xeploai,"kem");
		else if(dssv[i].dtb<5)
		strcpy(dssv[i].xeploai,"yeu");
		else if(dssv[i].dtb<7)
		strcpy(dssv[i].xeploai,"trung binh");
		else if(dssv[i].dtb<8)
		strcpy(dssv[i].xeploai,"kha");
		else
		strcpy(dssv[i].xeploai,"gioi");
		
		
		
	}
}
void indssv(sinhvien dssv[],int n)
{
	int stt=1;
	for(int i=0;i<n;i++)
	{
		
		cout<<stt<<"\t"<<dssv[i].hoten<<"\t"<<dssv[i].diemtin<<"\t"<<dssv[i].diemnn<<"\t"<<dssv[i].dtb<<"\t"<<dssv[i].xeploai<<endl;
		stt++;
	}
}
int main ()
{
	int n;
		    sinhvien dssv[100];
			nhapdssv(dssv,n);
			indssv(dssv,n);
			return 0;
}

Hai câu này khác hệ :smiley:

2 Likes

Là sạo ạ ??? Em chưa hiểu

Hàm gets() đã bị loại bỏ ở các phiên bản C++ mới rồi ạ, hình như từ C++11 gets đã bị loại bỏ. Do vậy bạn không nên dùng hàm này nữa

3 Likes

gets() là của C, thay bằng fgets(stdin, ...).

Cả hai hàm đều không bỏ phần dư ra khỏi stdin :smiley:

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