Code kiểm tra từ có tồn tại trong mảng bị sai

code này mình muốn dùng hàm strstr() để kiểm tra có từ “FEMALE” nào trong mỗi mảng không
nhưng mà nó đều ra cả 5 “FEMALE” —có gì đó sai sai
ai giúp mình với ạ :((((

#include <iostream>
#include <string.h>


bool FEMALE(char *all_student,int index){
	
	
	
    char *p1=strstr(all_student+index,"FEMALE");
    
	if(p1==NULL)
	return false;
	else 
	return true;
}


int main(){
	char **all_student=new char*[5];
	
	for (int i=0;i<5;i++){
		*(all_student+i)=new char[255];}
		strcpy(*(all_student+0),"SV1;OBAMA;MALE");
		strcpy(*(all_student+1),"SV2;YANJMAA,FEMALE");
		strcpy(*(all_student+2),"SV3;TRUMP;MALE");
		strcpy(*(all_student+3),"SV4;PUTIN;MALE");
		strcpy(*(all_student+4),"SV5;PEREIRA;FEMALE");
	
	
	for(int i=0;i<5;i++){
		
		std::cout<<*(all_student+i);
		std::cout<<"\n";
		
	}
	
	int dem=0;
	for(int i=0;i<5;i++){
		
		if(FEMALE(*(all_student),i))
		dem++;
		
	}

	std::cout<<"\nhas "<<dem<<" FEMALE";
	
	return 0;
}

Thế mà mình chạy thì kết quả lại là: has 0 FEMALE.
Bạn viết cái hàm FEMALE() với tham số “kì quái”.

Mình sửa thế này thì ra đúng:

if(FEMALE(*(all_student + i),0))

:face_with_raised_eyebrow:

2 Likes

cảm ơn anh ạ
nhờ anh mà em biết mình sai vì dư thừa tham số
mục đích ban đầu em cho tham số vào để xài như một chỉ mục trong mảng
và em nhận thấy ở hàm main() đã có “i” dùng để làm chỉ mục rồi nên việc khai báo thêm biến ở hàm chức năng FEMALE() là dư thừa
giờ lại chạy bình thường rồi ạ

#include <iostream>
#include <string.h>


bool FEMALE(char *all_student){
	
	
	
    char *p1=strstr(all_student,"FEMALE");
    
	if(p1==NULL)
	return false;
	else 
	return true;
}


int main(){
	char **all_student=new char*[5];
	
	for (int i=0;i<5;i++){
		*(all_student+i)=new char[255];}
		strcpy(*(all_student+0),"SV1;OBAMA;MALE");
		strcpy(*(all_student+1),"SV2;YANJMAA,FEMALE");
		strcpy(*(all_student+2),"SV3;TRUMP;MALE");
		strcpy(*(all_student+3),"SV4;PUTIN;MALE");
		strcpy(*(all_student+4),"SV5;PEREIRA;FEMALE");
	
	
	for(int i=0;i<5;i++){
		
		std::cout<<*(all_student+i);
		std::cout<<"\n";
		
	}
	
	int dem=0;
	for(int i=0;i<5;i++){
		
	if(FEMALE(*(all_student + i)))

		dem++;
		
	}

	std::cout<<"\nhas "<<dem<<" FEMALE";
	
	return 0;
}

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