文件样例

样例:解题与答题
在一文件里随机生成若干道加减乘除题,读入指定文件,然后在另一文件进行解答
本次只包含一个头文件,两个源文件,两个txt文本

"solve.h"

pragma once

define _CRT_SECURE_NO_WARNINGS

include <stdio.h>

include <string.h>

include <stdlib.h>

include <time.h>

void setQuestion();

void answerQuestion();

"solve.c"

include "solve.h"

void setQuestion()
{
int num1=0;
int num2=0;

char oper[]={'+','-','*','/'};
char ch=0;

FILE* fp=NULL;
fp=fopen("E:\c语言之家\question.txt","w");
//printf("%p\n",fp);
if(fp==NULL)
{
printf("打开失败");return;
}
srand(time(NULL));
int i;
for(i=0;i<50;i++)
{
num1=rand()%100+1;
num2=rand()%100+1;
ch=oper[rand()%4];

char str[50];
sprintf(str,"%d%c%d=\n",num1,ch,num2);//读入字符串
//printf("%s",str);
fputs(str,fp);
}

fclose(fp);

}

void answerQuestion()
{
FILE* fp1=fopen("E:\c语言之家\question.txt","r");
if(fp1NULL) printf("NO\n");
FILE* fp2=fopen("E:\c语言之家\solution.txt","w");
if(fp2
NULL) printf("NO\n");
char buf[50];
while(fgets(buf,sizeof(buf)-1,fp1))
{

//printf("%s",buf);
int num1=0;
int num2=0;
char oper;
sscanf(buf,"%d%c%d=",&num1,&oper,&num2);//数据拆分函数
double result;
switch(oper)
{
case '+':
result=num1+num2;
break;
case '-':
result=num1-num2;
break;
case '':
result=num1
num2;
break;
case '/':
result=num1*1.0/num2;
break;
}
char str[100];
sprintf(str,"%d%c%d=%g\n",num1,oper,num2,result);
//printf("%s",str);
fputs(str,fp2);
}

fclose(fp1);
fclose(fp2);
printf("OK");
}
main.c

include <stdio.h>

include <stdlib.h>

int main()
{
setQuestion();
answerQuestion();
}

posted @ 2021-02-07 22:35  empty_thought  阅读(108)  评论(0)    收藏  举报