저는 여기 새로 왔는데 이것은 제 첫 질문입니다.strstr 함수가 NULL을 반환하지 않습니다.
나는이 문제를 이미 조사했지만이 종류의 것을 찾지 못했습니다. 그래서 여기에 있습니다.
문자의 2 차원 배열을 사용하여 이름 데이터베이스에 대한 메뉴 기반 프로그램을 작성하고 있습니다. 아래는 내 주요 기능입니다.
int main(void)
{
char name[MAX][25] = { 0 };
char choice;
while (1) {
printf("******************menu****************\n");
printf("i: input\n");
printf("p: print\n");
printf("f: find\n");
printf("d: delete\n");
printf("s: sort\n");
printf("e: edit\n");
printf("q: quit\n");
printf("**************************************\n\n");
printf("Enter your choice: ");
scanf(" %c", &choice);
getchar();
switch (choice) {
case 'i':
input(name);
break;
case 'p':
print(name);
break;
case 'f':
find(name);
break;
case 'q':
return 0;
default:
printf("Invalid choice\n");
}
}
}
입력 및 인쇄 기능이 정상적으로 작동하지만 찾기 기능에 문제가 있습니다. 여기 있습니다.
void find(char (*p)[25])
{
int i;
char str[25];
if (count == 0) {
printf("Empty database\n");
return;
}
printf("Enter name to search: ");
fgets(str, 25, stdin);
str[strlen(str) - 1] = 0; //Removing new line character at the end of string.
for (i = 0; i < count; i++) {
if (strstr(p[i], str) != NULL); //Breaking the loop, when first occurence is found among all the names.
break;
}
if (i == count) {
printf("Not found\n"); // if loop is not terminated by "break" statement,
// that means strstr returned NULL for all names.
return;
}
printf("Names matching with %s\n", str);
for (i = 0; i < count; i++) {
if (strstr(p[i], str) != NULL); // Again looping to print all the matching names.
puts(p[i]);
}
}
count
은 입력 기능에서 증가하는 전역 변수입니다. 함수는 내가 횡설수설하는 이름을 제공하더라도 항상 true를 반환합니다. 우분투를 사용하고 있습니다. 16.04 gcc 5.3.1
strstr
에 중단 점을 사용하여 디버깅을 시도했지만 두 문자열을 올바르게 수신하지만 항상 haystack에 대한 포인터를 반환합니다.
__strstr_sse2 (haystack_start=0x7fffffffdcb0 "Imtiyaz", needle_start=0x7fffffffdc60 "abcd") at ../string/strstr.c:53
53 ../string/strstr.c : 해당 파일 또는 디렉토리가 없습니다.
건초 더미는 "Imtiyaz"
과 바늘 "abcd"
이며, 여기 반환 것입니다.
find (p=0x7fffffffdcb0) at name_data.c:126
여기에 무슨 문제가 있는지 이해하지 못하겠습니까? 내 편입니까?
그리고 이전에 strcasestr()
을 사용해 보았지만 컴파일러는 <string.h>
을 올바르게 포함했지만 컴파일러는 "암시 적 선언"이라는 경고를 throw합니다.
도와주세요.
편집 : 친구, 필자는 사용자가 내 프로그램을 올바르게 분석 할 수 있도록 입력 및 인쇄 기능도 표시합니다. 어느 쪽이든 괜찮습니다.
void input(char (*p)[25])
{
if (count == MAX) {
printf("Memory full\n");
return;
}
printf("Enter name: ");
fgets(p[count], 25, stdin);
p[count][strlen(p[count]) - 1] = 0; //Removing the new line character at the end of string.
count++;
}
void print(char (*p)[25])
{
int i;
if (count == 0) {
printf("Empty database\n");
return;
}
printf("********************************\n");
for (i = 0; i < count; i++) {
printf("%d %s\n", i + 1, p[i]); //printing names with serial numbers.
}
printf("********************************\n");
}
int switch-case처럼 다른 기능 (삭제, 검색 등)을 구현하지 않았습니다.
strstr()
당신이 무엇을 기대하고 있지 않는 이유에 대해서는
#define _GNU_SOURCE
, 당신이해야합니다 : 당신이 그것을 사용하는 소스 파일의 맨 위에이 작업을 수행 할 경우
'if' 명령문 중 두 개는 거기에 있어서는 안되는 후행하는';'을 가지고 있습니다. 코드는'scanf()'를 호출 할 때 오류를 검사하고 컴파일 할 때'fgets()' – user3629249
을 호출 할 때 항상 모든 경고 메시지를 활성화해야합니다. 그런 다음 경고를 수정하십시오. – user3629249