下面的代码应该从文件中读取,并将找到的数字分配到二维数组中以对其进行操作。
int newString[10][10];
int i,j,ctr;
FILE *fp;
char line[256];
fp = fopen("input.dat", "r");
for( i = 0; i < 10 ; i++){
for( j = 0; j < 10; j++){
newString[i][j] = 0;
}
}
j = 0;
ctr = 0;
while (fgets(line, sizeof(line), fp) != NULL){
for(i=0;i<=(strlen(line));i++){
if(line[i]==' '|| line[i]=='\0'){
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else{
newString[ctr][j]=line[i] - '0';
j++;
}
}
}
for( i = 0; i < 10 ; i++){
for( j = 0; j < 10; j++){
printf("%d ", newString[i][j]);
}
printf("\n");
}
fclose(fp);
文件如下
3
9 3 34 4 12 5 2
6 3 2 7 1
256 3 5 7 8 9 1
但是,我的输出如下
3 -38 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0
3 4 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0
1 2 0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0 0
2 -38 0 0 0 0 0 0 0 0
6 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0
您遇到的问题是,假设代码会将您的数字读为整数,但实际上是将其读为字符。当您将字符分配给整数时,它会通过ascii table隐式转换。您必须使用此字符变量将其转换为整数,并找出一种在出现两位数数字的情况下将其添加到先前值的方法。下面显示了while循环的外观概述,但我将让您弄清楚其余部分。
while (fgets(line, sizeof(line), fp) != NULL){
j = 0;//reset column to zero when you change lines
for(i=0;i<=(strlen(line));i++){
//only need some manipulation when the character read in is between 0 and 9
if(line[i]>='0' && line[i] <= '9'){
//use the ascii table linked to figure out how to convert the character value stored in line[i] to the integer value
//store that number in newString[ctr][i] NOTE: you need to figure out how to keep
//the values of the characters already stored in the array for example if 38 is the number
//your trying to read from the file the first character read will be 3 then you will read
//8 and need to figure out how to add that 8 to the 3 which is already stored to make 38
}
else{
j++;//move to next column
}
ctr++;//move to next row
}
首先,为什么要以好主的名字命名数组'newString'?
[第二,您的问题是该代码应该以整数形式读取您的数字,但实际上是以字符形式读取它的。当您将字符分配给整数时,它将通过ascii表隐式调用它。我下面的人将知道如何解决此问题,因为我不知道如何解决。祝你好运