088.批量计算数学题



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int f_calc(int p_v1, char p_sign, int p_v2) {
 switch (p_sign) {
 case '+':
  return p_v1 + p_v2;
 case '-':
  return p_v1 - p_v2;
 case '*':
  return p_v1 * p_v2;
 case '/': //这个地方有一个致命的地方
  if (!p_v2) {
   return -1;
  }
  else {
   return p_v1 / p_v2;
  }
 }
}

void main() {
 FILE* l_fp_read = fopen("1.txt", "r");
 if (!l_fp_read) {
  printf("打开读文件失败! ");
  system("pause");
  return;
 }

 int l_last_position = NULL;
 char l_read_line[50] = { NULL };
 char l_write_line[50] = { NULL };
 int * p_save = NULL;
 int l_count = NULL;

 while (!feof(l_fp_read)) {
  fgets(l_read_line, sizeof(l_read_line), l_fp_read);
  int l_this_position = ftell(l_fp_read);
  if (l_this_position != l_last_position) {
   l_last_position = l_this_position;
   int l_v1, l_v2;
   char l_sign;
   int l_result;
   sscanf(l_read_line, "%d%c%d=", &l_v1, &l_sign, &l_v2);
   l_result = f_calc(l_v1, l_sign, l_v2);
   sprintf(l_write_line, "%d%c%d=%d ", l_v1, l_sign, l_v2, l_result);
   //在C语言中,只要是系统内置的函数,如果里面包含scanf这个关键字.
   //你一定要使用取地址符号才能正常使用.
   l_count++;
   p_save = (int *)realloc(p_save, l_count*sizeof(int));
   int l_sizecount = strlen(l_write_line) + 1;
   p_save[l_count - 1] = (int)calloc(l_sizecount, sizeof(char));
   strcpy((char *)p_save[l_count - 1], l_write_line);
  }
 }

 FILE* l_fp_write = fopen("1.txt", "w");
 if (!l_fp_write) {
  printf("打开写文件失败! ");
  system("pause");
  return;
 }
 for (size_t i = 0; i < l_count; i++) {
  fputs((char *)p_save[i], l_fp_write);//ctrl+J
  free((char *)p_save[i]);
 }

 free(p_save);
 fclose(l_fp_read);
 printf(" 自动答题工作完成 ");
 system("pause");

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int count (int one, int tow, char symbol) {
switch (symbol) {
case '+':
return one + tow;
case '-':
return one - tow;
case '*':
return one * tow;
case '/':
if (!tow) {
return 0;
}
else { return one / tow; }
}
}


void main() {
FILE*read = fopen("1.txt", "r");
if (!read) {
printf("文件为空");
system("pause");
return;
}
int kong = NULL;
char pp[50] = { NULL };
char bb[50] = { NULL };
int *shenqing=NULL;
int counter = NULL;
while (!feof(read)) {
fgets(pp, sizeof(pp), read);
int shaomiao = ftell(read);
if (shaomiao != kong) {
int one; int tow; char symbol;
sscanf(pp, "%d%c%d=",&one, &symbol, &tow);
int result=count(one, tow, symbol);
sprintf(bb, "%d%c%d=%d ", one, symbol, tow, result);
counter++;
shenqing = (int*)realloc(shenqing, counter*sizeof(int));
int cc = strlen(bb)+1;//加是因为1+1= NULL,NULL是结束标志
shenqing[counter - 1] = (int)calloc(cc, sizeof(char));
strcpy((char*)shenqing[counter - 1], bb);
}

}
FILE*write = fopen("1.txt", "w");

for (size_t i = 0; i < counter; i++)
{
fputs((char*)shenqing[i], write);
free((char*)shenqing[i]);
}

free(shenqing);
fclose(read);
system("pause");

}

原文地址:https://www.cnblogs.com/xiaodaxiaonao/p/9053985.html