title: How to read and print all the different data types together from a file in C programming
body: <p>My code is given below. If run this code then even though the text file gets created correctly, for some reason junk values get printed in the console. When I include the string then only the string gets read and printed correctly in the console window and I get junk value for the rest of the variables but when I remove the string completely then I get correct values for rest of the variables. Why is this issue occurring and how to fix it ?</p>
  
  <p>This is the code:  </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void) {
      char str[] = "a string";
      char str2[50];
      char ch ='a';
      char ch1;
      int num = 12;
      int num1;
      float deci = 51.15;
      float deci1;
      FILE *new;
  
      new = fopen("a.txt","w");
      if (new == NULL) {
          printf("Error! file not found! \n");
      }
      fprintf(new, "%s\n", str);
      fprintf(new, "%c\n", ch);
      fprintf(new, "%d\n", num);
      fprintf(new, "%.2f\n", deci);
  
      fclose(new);
  
      new = fopen("a.txt", "r");
      if (new == NULL) {
          printf("Error! file not found!  \n");
      }
  
      fscanf(new, "%[^\n]s", str2);
      //str2[7]='\0';
  
      fflush(stdin);
      fscanf(new, "%c", &amp;ch1);
      fscanf(new, "%d", &amp;num1);
      fscanf(new, "%f", &amp;deci1);
  
      //fclose(new);
  
      printf("string: %s character: %c integer: %d float: %f", str2, ch1, num1, deci1);
      //enter code here
      fclose(new);
  }
  </code></pre>