每个交易都在一个新行中,动作(撤销或借记)由逗号或单个空格分隔。有人可以帮我从这里出去吗?我还需要将数据存储到一个数组中并确定信息在这样的文本文件中有多少交易,w表示撤销,d表示存款,我需要从文件中将数据存入数组,(transactions1和transaction2)在新线上)假设它们是三个交易,其中两个显示在下面
transaction1,w 3000 transaction2,d 4000 这是我生成的代码,但是程序崩溃并且没有打印出来 我用逗号和单个空格尝试了它,但stil不起作用
#include <stdio.h>
#include <stdlib.h>
int main()
{//open main
int i;
char array1[3];//array to store type of transaction, 'w' or'd' depending on withdraw or deposit
int array2[3];//array to store amount involved in transaction
FILE *fptr = fopen("transactions.txt", "r");
if((fptr = fopen("transactions.txt", "r"))==NULL)
printf("error in opening file");
for (i = 0; i<3 ; i++)
{
fscanf(fptr,"%s");
fscanf(fptr, "%c", &array1[i]);
fscanf(fptr, "%d", &array2[i]);
}
//checking whether the values and type of transaction successfully stored in respective arrays
for (i= 0; i<3; i++)
{
printf("%c", array1[i]);
printf("%d", array2[i]);
}
return 0;
}//close main
答案 0 :(得分:1)
提到BLUEPIXY时,您需要使用fscanf(fptr,"%*[^,],");
代替fscanf(fptr,"%s");
来阅读并放弃第一个','
以外的所有内容,然后您可以阅读一个字符和一个字符文件中的整数。
而且,如果文件未正确打开,则必须返回。
#include <stdio.h>
#include <stdlib.h>
int main()
{//open main
int i;
char array1[3];//array to store type of transaction, 'w' or'd' depending on withdraw or deposit
int array2[3];//array to store amount involved in transaction
FILE *fptr;
if((fptr = fopen("transactions.txt", "r"))==NULL)
{
printf("error in opening file");
return 0;
}
for (i = 0; i<3 ; i++)
{
fscanf(fptr,"%*[^,],");
fscanf(fptr, " %c", &array1[i]);
fscanf(fptr, "%d", &array2[i]);
}
//checking whether the values and type of transaction successfully stored in respective arrays
for (i= 0; i<3; i++)
{
printf("%c", array1[i]);
printf(" %d", array2[i]);
}
return 0;
}//close main
我使用了以下文件内容:
transaction1,w 4000
transaction2,d 3000
transaction3,d 5000
答案 1 :(得分:0)
请尝试以下,我没有测试
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char array1[3];
int array2[3];
FILE *fptr = fopen("transactions.txt", "r");
if(fptr == NULL)
{
printf("error in opening file");
return -1;
}
for (i = 0; i<3 ; i++)
{
fscanf(fptr, "%c %d", &array1[i], &array2[i]);
}
for (i= 0; i<3; i++)
{
printf("%c %d\n", array1[i], array2[i]);
}
fclose(fptr);
return 0;
}//close main