c++ 如何读取文本中的小数数组
来源:百度知道 编辑:UC知道 时间:2024/05/26 19:21:01
这是d:/ 下的一个文本文件 存放着小数数组
0 -0.2 0.2 0.2 -0.2
-0.2 0 0.2 0.2 0.6
0.2 0.2 0 -0.2 0.2
0.2 0.2 -0.2 0 0.2
-0.2 0.6 0.2 0.2 0
如何用C++进行读入呢
ifstream ww("ww.txt",ios::binary);
while(ww)
{
for( i=0;i<5;i++)
for(j=0;j<5;j++)
{
ww>>w[i][j];
}
}
这样读出后 输出结果
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
Press any key to continue
改成如下程序时
ifstream ww("quanzho
0 -0.2 0.2 0.2 -0.2
-0.2 0 0.2 0.2 0.6
0.2 0.2 0 -0.2 0.2
0.2 0.2 -0.2 0 0.2
-0.2 0.6 0.2 0.2 0
如何用C++进行读入呢
ifstream ww("ww.txt",ios::binary);
while(ww)
{
for( i=0;i<5;i++)
for(j=0;j<5;j++)
{
ww>>w[i][j];
}
}
这样读出后 输出结果
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061
Press any key to continue
改成如下程序时
ifstream ww("quanzho
为什么用二进制形式找开呢?利用类ifstream对<<运算符的重载,可直接读double类型数据,非常方便简单.程序如下
double w[5][5]
ifstream ww("quanzhong.txt");
for( i=0;i<5;i++)
for(j=0;j<5;j++)
{
ww>>w[i][j]
}
for( i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
char buf[10] = {0};
int n = 0;
char ch = ww.get(c);
if (ch == 0x20 || ch == 0x0D)
{
w[i][j]= atof(buf);
}
else if (ch == 0x0A)
{
continue;
}
else
{
buf[n++] = ch;
}
}
}
你用文本读取看看,不要用2进制读取。