C语言如何读取文本文档里的数据并计算?

C语言如何读取文本文档里的数据并计算? 如文本文档里的内容: 5,10;(第一行就这两个数值) 计算就是把两个数相加,计算结果写在另新建文本文档的第一行。

#include <iostream>
using namespace std;
int main()
{
    freopen("testin.txt","r",stdin);
    freopen("testout.txt","w",stdout);
    int n;
    cin>>n;
    cout<<n<<endl;
    fclose(stdin);
    fclose(stdout);
    return 0;
}

如下图片:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-08-07
/假设txt文件名a.txt
#include <stdio.h>
struct point {
char No[6];
double X;
double Y;
int R;
double lo;
} poi[11];
int main()
{
int i;
FILE* fp = fopen("a.txt", "r");
if(fp==NULL){printf("cannot open file a.txt\n"); return 1;}
for(i=0; i<11; i++)
fscanf(fp, "%s%lf%lf%d%lf",&poi[i].No,&poi[i].X,&poi[i].Y,&poi[i].R,&poi[i].lo);
//已经数据全部读进
fclose(fp);
for(i=0; i<11; i++)//显示打印出来;
printf("%d\n",a+b);
return 0;
}
第2个回答  2012-09-08
#include<stdio.h>
int main(int argc,char *argv[])
{
FILE *fp1,*fp2;
int a,b,c;
char buf[10];

if(argc < 3)
{
perror("Uasge is error.\n");
return -1;
}
if((fp1 = fopen(argv[1],"r")) < 0)
{
perror("Fail to fopen.\n");
return -1;
}
if((fp2 = fopen(argv[2],"w+")) < 0)
{
perror("Fail to fopen2.\n");
return -1;
}
fgets(buf,10,fp1);
a = atoi(buf); //字符强转为整形,将字符5强转为int 5
b = atoi(buf+2); //argv[1]中存的是5,10,将字符串10强转为int 10
fprintf(fp2,"The result is %d.\n",a + b);

return 0;
}
我是在linux下写的
第3个回答  2012-09-08
#include<stdio.h>
int main()
{
int a,b;
freopen("C:\\a.txt","r",stdin);//从A里面读
freopen("C:\\b.txt","w",stdout);//写到B里面
scanf("%d,%d",&a,&b);
printf("%d\n",a+b);
return 0;
}本回答被网友采纳
相似回答