博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 语言爱好者_语言都是相通的,学好一门语言,再学第二门语言就很简单,记录一下我复习c语言的过程。...
阅读量:4679 次
发布时间:2019-06-09

本文共 1548 字,大约阅读时间需要 5 分钟。

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

为了将本人的python培训提高一个层次,本人最近买了很多算法的书.

这个书上的代码基本都是c语言实现的,c语言很久没有用了,复习一下c语言。

买了一本英文书head first c 第94页有这样的代码。代码很简单,但就是不出要的结果。

#include

#include

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.

转载地址:http://vtfkp.baihongyu.com/

你可能感兴趣的文章
实验11——指针的基础应用
查看>>
Go实现发送解析GET与POST请求
查看>>
Girls Like You--Maroon 5
查看>>
FZU 1343 WERTYU --- 水题
查看>>
angularjs 中使用 service 在controller 之间 share 对象和数据
查看>>
禁止在 .NET Framework 中执行用户代码。启用 "clr enabled" 配置选项
查看>>
JSON、闭包和原型----透视Javascript语言核心
查看>>
[苹果]苹果AppStore应用审核标准
查看>>
lxr看代码的时候出现中文乱码问题
查看>>
CImageList使用指南(转)
查看>>
常量like数据库表中的列
查看>>
VC2012编译CEF3-转
查看>>
Log4net的配置-按照日期+文件大小混合分割
查看>>
const char*、char*、char* const、char[]、string的区别
查看>>
『cs231n』绪论
查看>>
SQL学习笔记:基础SQL语句
查看>>
python管理网络设备的一些模块
查看>>
VirtualProtect、VirtualLock、VirtualUnlock
查看>>
Stl
查看>>
mysql在windows下主从同步配置
查看>>