我正在用Head First C書學習C編程。 所以我想編譯這段代碼,我們可以發現在94頁:在自動存儲塔代碼中的錯誤(頭先C)
#include <stdio.h>
#include <string.h>
char tracks[][80] = {
"I left my heart in Harvard Mead School",
"Newark, Newark - a wonderful town",
"Dancing with a Dork",
"From here to maternity",
"The girl from Iwo Jima",
};
void find_track(char search_for[])
{
int i;
for (i = 0; i < 5; i++)
{
if (strstr(tracks[i], search_for))
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
int main(void)
{
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
看這個輸出:
----------------------------------------------------------------- ./jukebox -- Search for: town -- kawaban9a-14H:~/Code/C/Head_C/Chapter_3$ (so, nothing happens) -- -----------------------------------------------------------------
這沒關係,沒有編譯器的投訴,但是當我運行它,沒有結果。 我多次閱讀此代碼,我無法理解爲什麼,錯誤在哪裏? 如果有人能幫助我,我將不勝感激。
幾分鐘過後...
感謝您的朋友cnicutar的回答,幫助我找出問題'\n'
。 我通過在調用find_track()
函數之前插入一段代碼解決了這個問題。
檢查出來:
int main(void)
{
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
size_t ln = strlen(search_for) - 1;
if (search_for[ln] == '\n')
search_for[ln] = '\0';
find_track(search_for);
return 0;
}
可能重複[C代碼字符串匹配\ [頭部一次C類似乎\]不工作(http://stackoverflow.com/questions/12019607/ c-code-for-string-matchinghead-first-c-doesnt-scone-to-work) – gnat
我今天問過,所以檢查答案。 [Here](http://stackoverflow.com/questions/27720837/no-output-in-terminal-head-first-c) –