How to read and print all the different data types together from a file in C programming

Viewed 556

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 ?

This is the code:

#include <stdio.h>
#include <stdlib.h>

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", &ch1);
    fscanf(new, "%d", &num1);
    fscanf(new, "%f", &deci1);

    //fclose(new);

    printf("string: %s character: %c integer: %d float: %f", str2, ch1, num1, deci1);
    //enter code here
    fclose(new);
}
1 Answers

If I'm not wrong the error is here:

fscanf(new, "%[^\n]s", str2); 

Try to change it with:

fscanf(new, "%[^\n]\n", str2);

This does work for me.

Related