VC++读取文本文件里的数据到数组中
10111100000000001010001001
01110100010000000000110001
00110000000000000001000000
10110110000100001010101001
11000010000100010001000111
00101100101100100011000010
11101100000010011001000001
11010100010010001011000011
10101100000000100001000001
10111100000100100001000001
01001100011000011011000001
11100000011000011011000100
01011010101000000010111001
11001000010010011010110001
10111000000000101010011001
00101110010100000010101001
10101010000000110001000001
00100110100000100000111001
10110010101100100010100011
10101110000100100011000001
01011110100000100010110011
00110110111000111000001111
01011110011000000010011000
00011110000100100000010000
01011110110101000110000000
11110001001000110110101001
11110010100001001000011001
11010100000100001010101111
10111010111000100010101001
11010100100100111000111000
11100100011101000110111111
01001010010101001011000111
00101100101000000010101001
10110110000100001010111001
10110110000100100000111001
00101110101100111000010001
10110110000010100010010001
11101100100101010100111001
11000100100100100010100001
10111000111100100000101100
10111010000100001000001000
11001110110100001010110001
11110001110010100010100001
11101100011000100000110001
01010010001010000000111010
10111110010000100000011001
11010010000101000111000000
10101110000000100011000001
00110010000000100001000001
10110100000100000011000001
想读入到一个整数型数组中去。这是我写的程序~没有错误 但是达不到效果
请大虾帮忙看看应该怎么改 谢谢
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#include "stdlib.h"
#define N 50
void main()
{
FILE *f;
int i=0,j=0;
int Property[N][25];
char str[100],*pNext;
cout<<"请输入数据集合文件名称"<<endl;
cin>>str;
f=fopen(str,"r");
if(f==NULL) {cout<<"Error, file don't open!"<<endl; return;}
while(!feof(f))
{
fgets(str,100,f);
pNext=str;
for(j=0;j<25;j++)
{
Property[i][j]=atoi(pNext);
cout<<Property[i][j]<<endl;
pNext=pNext+1;
}
i++;
}
getchar();
fclose(f);
}
读入数据完全不对 比如Property[0][0]应该等于1 运行结果为-115585375~~囧啊 展开
atoi(pNext); 你这样把一个字符转换成int是不行的,你不用转换pNext它即可以看做是个字符,也可以看做是个int类型,实际上你的Property[0][0]保存的并不你想要看到1 0字符串,而是1 0 字符串的ASC码。你想看到1 0值的话必需用它的ASC减48。
你的str是个指针,不知道你还要定义一个pNext是做什么的?
你把上面的10字符串保存成aa.txt(扩展名也可以是dat)放在当前目录。
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#include "stdlib.h"
#define N 50
void main()
{
FILE *f = NULL;
int i=0,j=0;
int Property[N][25];
char str[100];
f=fopen("aa.txt","rb");
if(f==NULL) {cout<<"Error, file don't open!"<<endl; return;}
while(!feof(f))
{
fgets(str, 100, f);
for(j=0;j<25;j++)
{
Property[i][j] = str[j] - 48;
cout<<Property[i][j]<< " ";
}
cout<<endl;
i++;
}
getchar();
fclose(f);
}
你读取数据的时候用的是fgets,这样的话一个1 0只会占用一个字符的位置,你定义数组的大小25就可以了。
如果你确实想用pNext的话,你上面的用法也有错误的。
把Property[i][j]=atoi(pNext);改成
Property[i][j]=atoi(*pNext);
上面的是你取的是指针的地址,而不它指向的值,这也就是你出现的乱码。