今天我正在尝试使用C on linux mint上的文本文件进行练习,但是它没有用(文本没有显示)。请帮我解决一下。
#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;
}
当我在终端上运行此代码时,我得到
非常感谢。
答案 0 :(得分:0)
考虑使用fgets捕获输入,使用sscanf来解析输入。检查sscanf的返回以查看是否成功。这允许输入空行来终止程序。比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;
}