我正在尝试编写一个程序,以编辑包含代码块上用户费用的文本文件。
第一阶段::文件名为“ abc.txt”。它说明了当前金额和每个日期的支出。通过循环,我将“ abc.txt”复制到另一个文件“ test.txt”。
第二阶段:,在另一个循环中,我要求用户添加一个新的日期和新金额,该金额将被减去或添加到总金额中。
第三阶段:我关闭两个文件,并使用另一个循环将“ test.txt”文件(包含所有更新的信息)复制到原始abc.txt”文件。
问题出在最后阶段;复制文本时,不保留空格。
如果要使用我的代码,则应该有2个文本文件,分别为“ abc.txt”和“ test.txt”。将“测试”文件保留为空白,然后在“ abc”文件中输入以下内容:
[0] Total amount: 79179 [1]
[1]
[1]
[1]
[0] Date: 1.1.19 [1]
[0] Sub: 10000 70000 [1]
[1]
[0] Date: 2.1.19 [1]
[0] Add: 10000 80000 [1]
[1]
[0] Date: 3.1.19 [1]
[0] Sub: 499 79501 [1]
[1]
[0] Date: 4.1.19 [1]
[0] Sub: 322 79179 [1]
[1]
然后运行以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * filepointer;
filepointer=fopen("abc.txt","r");
char name[100];
char name1[1000];
int num;
int old_amount;
char date[20];
int flag=0;
int amount;
char action[10];
int tit;
FILE *test;
test=fopen("test.txt","w");
fscanf(filepointer,"%s %s %s %d", &name, &name, &name, &amount );
printf("The total amount: %d\n",amount);
while(!feof(filepointer))
{
fscanf(filepointer,"%s",name );
if(strcmp(name,"[1]")==0)
{
printf("\n");
fprintf(test,"[1]\n");
fscanf(filepointer,"%s ",name );
}
printf("%s ",name);
fprintf(test,name);
fprintf(test," ");
}
printf("Enter date: ");
scanf("%s",&date);
printf("date: %s\n ",date);
fprintf(test,"\n[0] Date: ");
fprintf(test,date);
fprintf(test," [1]\n");
while(flag==0)
{
fflush(stdin);
printf("What is th amount: ");
scanf("%d",&num);
printf("[0] %d\nstate action [S] [A]: ",num);
scanf("%s",&action);
if(strcmp(action,"a")==0 || strcmp(action,"A")==0)
{
fprintf(test,"\n[0] Add: %d ",num);
amount=amount+num;
fprintf(test,"%d [1]\n",amount);
printf("OK");
}
if(strcmp(action,"s")==0 || strcmp(action,"S")==0)
{
fprintf(test,"\n[0] Sub: %d ",num);
amount=amount-num;
fprintf(test,"%d [1]\n",amount);
printf("OK");
}
printf("\nDo you wish to add another value?[Y] [N]\n");
scanf("%s",&action);
if(strcmp(action,"n")==0 || strcmp(action,"N")==0)
{
flag=1;
}
}
fclose(test);
fclose(filepointer);
FILE * text;
text=fopen("test.txt","r");
FILE *abc;
abc=fopen("abc.txt","w");
fprintf(abc,"\n[0] Total amount: %d [1]\n",amount);
while(!feof(text))
{
fscanf(text,"%s",&name1 );
if(strcmp(name1,"[1]")==0)
{
//printf(" GOT IT \n");
fprintf(abc,"[1]\n");
fscanf(text,"%s ",&name1 );
}
printf("%s ",name1);
fprintf(abc,"%s ",name1);
fprintf(abc," ");
}
return 0;
}
当我在项目文件中运行它时,它可以正常工作,但是当我作为应用程序运行时,它会带来麻烦……有什么想法吗?