语言都是相通的,学好一门语言,再学第二门语言就很简单,记录一下我复习c语言的过程。

语言都是相通的,学好一门语言,再学第二门语言就很简单,记录一下我复习c语言的过程。
为了将本人的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.


你可能感兴趣的:(语言都是相通的,学好一门语言,再学第二门语言就很简单,记录一下我复习c语言的过程。)