首页 > 解决方案 > 遍历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 开发人员解释为什么会发生这种情况,以及如何实现我的目标吗?

标签: cstringcharacter

解决方案


%s打印一个以空字符结尾的字符串,即从printf参数指向的字符开始的多个字符,直到遇到空字符。

如果要打印单个字符,则需要%c然后对应的参数 toprintf应该是 a int(或提升char),而不是 a char*,所以 just line[j], not &line[j]

此外,您还需要检查fgetsnull 的返回值,以验证它是否成功。


推荐阅读