我是新來的,這是我的第一個問題。strstr函數不返回NULL
我已經搜索過這個問題,但沒有找到這種類型的東西。 所以就這樣了。
我正在寫一個名稱數據庫的菜單程序,使用2d字符數組。以下是我的主要功能。
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
這裏是一個全局變量,它在輸入函數中遞增。 strstr
函數總是返回true,即使我提供了一些亂碼名稱。 我使用的是Ubuntu 16.04 gcc 5.3.1
我試着用斷點調試strstr
,它正確地接收了兩個字符串,但總是將指針返回乾草堆。
__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>
。
請幫幫我。
編輯:好的朋友,我也會顯示輸入和打印功能,讓你的人正確地分析我的程序。順便說一句,工作正常。
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。
兩個'if'語句有一個尾部';'不應該在那裏。代碼應該在調用'scanf()'時檢查錯誤,並且在編譯時調用'fgets()' – user3629249
時,始終啓用所有警告消息。然後修復這些警告。 – user3629249