c - 遍历C中的一个字符
问题描述
我来自 Fortran 社区,所以请原谅我问了这么简单的问题。
我有以下内容:
char temp_line[250];
char *line;
// read in a file and get first line
line = fgets(temp_line, 250, fp) ;
// Now I want to iterate through each character in line
// my line in reality reads: "H AR "
// So I want to get from the loop my first increment will be H, then empty string, then "A" then "R" etc.
// I am doing following
for (int j =0; line[j] != '\0';j++) printf("%i : %s",j, &line[j])
// the results is:
// 0 : H AR
// 1 : AR
// 2 : AR
// 3 : R
好像是在往反方向发展。有人可以向新的 C 开发人员解释为什么会发生这种情况,以及如何实现我的目标吗?
解决方案
%s
打印一个以空字符结尾的字符串,即从printf
参数指向的字符开始的多个字符,直到遇到空字符。
如果要打印单个字符,则需要%c
然后对应的参数 toprintf
应该是 a int
(或提升char
),而不是 a char*
,所以 just line[j]
, not &line[j]
。
此外,您还需要检查fgets
null 的返回值,以验证它是否成功。
推荐阅读
- amazon-web-services - 撤销 Amazon S3 存储桶或对象权限
- node.js - 如何在 Node.js 和 React 中分离客户端、API、管理员?
- javascript - 如何通过对象键名从对象数组中删除对象?
- python - 在熊猫数据框中创建父子对字典
- batch-file - 使用通配符文件夹批量复制某些文件
- php - 在 jQuery 中使用 post() 生成元素后对元素进行操作
- getuikit - 如何更改 UIkit.notification 的宽度?
- c# - 反转显示字符串的顺序
- wordpress - wp_options 中的 Wordpress cron 值太大
- java - 为什么 Java Web 应用程序是使用 Java SE SDK 开发的