如何从文件中读取一个数据到C++程序中,并进行运算(在线等)

来源:百度知道 编辑:UC知道 时间:2024/07/05 03:44:10
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int i,j;
float a[4097];
FILE *fp;
if((fp=fopen("e:\\123.txt","r"))==NULL)
{
printf("1cannot open file!\n");
return 0;
}
for(j=1;j<=4096;j++)
fscanf(fp,"%f",&a[j]);
fclose(fp);
float x,R=0.5,b;
x=a[j];
if(x>R)
b=12.56*(1+0.75*(x/R)*(x/R));
else
{
b=12.56*(0.5*(R/x)*(R/x)*(R/x)+0.5625*(R/x)*(R/x)*(R/x)*(R/x)*(R/x));
}

cout<<"b="<<b<<endl;
}
高手给看看;

经过for循环后,j= 4097,所以下面的语句导致数组访问越界。
x=a[j];

假设

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
string str;
ifstream infile("number.txt",ios::binary);

int number[65536] = {0};
infile>>str;
int i=0;
while(1)
{
number[i++] = atoi(str.c_str());
infile>>str;
if( str.empty() ) break;
}

return 0;
}
至于读取指定的第n行数据,肯定需要一个参数n,ifstream有个函数getline但没这个参数,只能这样略过n-1行后再读的就是第n行:(
for(int i=0; i<n-1; i++) infile.getline(buffer, 1024);

其实从文件读的数据一般都是字符,要想进行运算必须进行处理
string s;
ifstream infile;
infile.open("test.txt");//
while(getline(infile,s))
{
int a; //存放数据
for( istringstream sin(s) ; sin>>a ; a=a-"0");//你可以添加运算
}
不知道是不是你想要的
如果你是想读取表达式进行运算,那就比较麻烦了

char sRead[1024];