[英]Iterate through a character in C
I am from the Fortran community so forgive for asking such a simple question.我来自 Fortran 社区,所以请原谅我提出这么简单的问题。
I have the following:我有以下几点:
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
Seems like it is going in reverse direction.好像是往相反的方向发展。 Can somebody explain to a new C developer why this is occuring, and how I can achieve my objective?
有人可以向新的 C 开发人员解释为什么会发生这种情况,以及我如何实现我的目标?
%s
prints a null-terminated string, ie multiple characters starting from the pointed-to one from the printf
argument, until a null character is encountered. %s
打印一个以空字符结尾的字符串,即从printf
参数中指向的字符开始的多个字符,直到遇到空字符。
If you want to print a single character, you need %c
and then the corresponding argument to printf
should be a int
(or promoted char
), not a char*
, so just line[j]
, not &line[j]
.如果要打印单个字符,则需要
%c
,然后printf
的相应参数应该是int
(或提升的char
),而不是char*
,因此只需line[j]
,而不是&line[j]
。
Also, you are meant to check the return value of fgets
against null, to verify that it succeeded.此外,您打算根据 null 检查
fgets
的返回值,以验证它是否成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.