語言都是相通的,學好一門語言,再學第二門語言就很簡單,記錄一下我複習c語言的過程。
爲了將本人的python培訓提升一個層次,本人最近買了不少算法的書.python
這個書上的代碼基本都是c語言實現的,c語言好久沒有用了,複習一下c語言。
買了一本英文書head first c 第94頁有這樣的代碼。代碼很簡單,但就是不出要的結果。
#include <stdio.h>
#include <string.h>
char names[][80] = {
"David Bowie",
"Julia Roberts",
"George Bush",
"Robin Hanson",
};
void find_name(char search_for[])
{
int i;
for (i = 0; i < 4; i++) {
if (strstr(names[i], search_for)) {
printf("Name %i: '%s'\n", i, names[i]);
}
}
}
int main()
{
char search_for[80];
printf("Enter search term: ");
fgets(search_for, 80, stdin);
find_name(search_for);
return 0;
}
本人加多個printf()測試,終於找到緣由是fgets(search_for, 80, stdin);這條語句的事。
後來修改成scanf("%79s",search_for);獲得要的結果。
後來再搜google這個函數的原型,這個fgets函數會讀入換行符號"\n".最後找到一段代碼,老外實現的
怎麼去掉後面的換行符。
The fgets function reads characters from the stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string.
A newline character makes fgets() stop reading and is included in the string. Which means that when you type 「David Bowie」 the search string will contain 「David Bowie\n」, which does not equal names[0]:
{‘D’, ‘a’, ‘v’, ‘i’, ‘d’, ‘ ‘, ‘B’, ‘o’, ‘w’, ‘i’, ‘e’, ‘\n‘, ‘\0′} does not equal {‘D’, ‘a’, ‘v’, ‘i’, ‘d’, ‘ ‘, ‘B’, ‘o’, ‘w’, ‘i’, ‘e’, ‘\0′}
The solution? Replace the newline character by a NULL character:
size_t len = strlen(search_for) - 1;
if (search_for[len] == '\n');
search_for[len] = '\0';
This works because the NULL character marks the end of any character array that is a string. In other words, the string ends at the first null character.
算法