Narun Nun-a-nan Narun Nun-a-nan - 3 months ago 4
C Question

Using text file it's not working

today i am trying to practice using text file by c on linux mint, but it's not working (text not show). please help me to solve it.(click on this text string to see a picture)

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

int main()
{
int account;
char name[30];
float balance;
FILE *fp;
if((fp = fopen("tin", "w")) == NULL) {
printf("File could not be opened\n");
exit(1);
}
else {
printf("Enter the account, name, and balance.\n");
printf("Enter EOF to end input.\n");
printf("?");
scanf("%d%s%f", &account, name, &balance);
while(!feof(stdin)) {
fprintf(fp, "%d %s %2.f\n", account, name, balance);
printf("?");
scanf("%d%s%f", &account, name, &balance);
}
fclose(fp);
}
return 0;
}


when i run this code on my terminal (click on this text string to see a picture)

Thank you very much.

Answer

Consider using fgets to capture input and sscanf to parse the input. Check the return of sscanf to see if is was successful. This allows the input of a blank line to terminate the program. A little more convenient than EOF.

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

#define SIZE 256

int main()
{
    int account;
    char name[30];
    char input[SIZE];
    float balance;
    FILE *fp;
    if((fp = fopen("tin", "w")) == NULL) {
        printf("File could not be opened\n");
        exit(1);
    }
    else {
        do {
            printf("Enter the account, name, and balance.\n");
            printf("Enter at ? to end input.\n");
            printf("?");
            if ( fgets ( input, SIZE, stdin)) {
                if ( ( sscanf ( input, "%d%29s%f", &account, name, &balance)) == 3) {
                    printf ( "adding input to file\n");
                    fprintf(fp, "%d %s %2.f\n", account, name, balance);
                }
                else {
                    if ( input[0] != '\n') {
                        printf ( "problem parsing input\nTry again\n");
                    }
                }
            }
            else {
                printf ( "problem getting input\n");
                exit ( 2);
            }
        } while( input[0] != '\n');
        fclose(fp);
    }
    return 0;
}
Comments