-1

I am from the Fortran community so forgive for asking such a simple question.

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?

ATK
  • 1,296
  • 10
  • 26

1 Answers1

3

%s prints a null-terminated string, i.e. multiple characters starting from the pointed-to one from the printf argument, until a null character is encountered.

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].

Also, you are meant to check the return value of fgets against null, to verify that it succeeded.

walnut
  • 21,629
  • 4
  • 23
  • 59
  • Okay, that is what I am looking for. I know this is not part of the question. But I initially wanted to use these single characters in a `strcmp` function. Do I just use a fprintf to write to a single char variable or is there aanother way doing it Since I cannot use `line[j]` as an argument to `strcmp` – ATK Mar 23 '20 at 09:53
  • @ATK I am not sure what you mean. You don't need `strcmp` to compare individual characters. You can compare them directly with `==`. `strcmp` is needed to compare two null-terminated strings. – walnut Mar 23 '20 at 09:55
  • Okay I think I got it. So I can simply do: `line[j] == "!"` to e.g. check if that character has an "!" – ATK Mar 23 '20 at 09:57
  • @ATK Not quite, `"!"` is a *string literal*. It is basically a pointer to a null-terminated string. If you want to compare characters, you need a *character literal*, which would be `'!'`. – walnut Mar 23 '20 at 09:57
  • Cheers That works. I need to readup how the string/character works in c. Thanks for help ! – ATK Mar 23 '20 at 09:59