所以我试图从文件中读取一个矩阵(我确信有更好的方法来做它而不是我这样做)。我很难弄清楚如何从文件中读取每个单词(意味着矩阵的每个条目),所以决定读取每一行并使用我在stackexchange中找到的名为strtok
的东西。
我的main()
内部看起来像这样
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <malloc.h>
#include <time.h>
#include <string.h>
int main(){
FILE *f;
int nmatrix=3;
int nmax=3;
int something;
int number, count, count2, i, j;
srand(time(NULL));
size_t len = 0;
ssize_t read;
char * line = NULL;
char * pch;
int ia;
int (*B)[nmatrix][nmatrix] = malloc(nmatrix * nmatrix * sizeof(int));
while(nmatrix<=nmax){
// Creation of Matrix
f = fopen("matrix.txt", "w");
for(count = 1; count <= nmatrix; count ++){
for(count2 = 1; count2 <= nmatrix; count2 ++){
number = rand()%9;
fprintf(f, "%s%d ", " ", number);
}
fprintf(f, "%s\n", " ");
}
fclose(f);
// Reading Matrix
f = fopen("matrix.txt", "r");
i=0;
while((read = getline(&line, &len, f)) != -1) {
printf("%s\n", line);
pch = strtok(line," ,.-");
j=0;
while (pch != NULL & j<nmatrix){
ia= (int)*pch-48;
*B[i][j]= ia;
pch = strtok(NULL, " ,.-");
j=j+1;
}
i=i+1;
}
fclose(f);
nmatrix=nmatrix+1;
}
return 0;
}
终端中的第一个输出是如果行*B[i][j]= ia;
被删除,第二个输出是。第一个输出读取文件中的所有行,第二个输出不读取最后一行。为什么? (输出看起来不同,因为矩阵是随机生成的。)
我对所有事情都很陌生,特别是指针,所以如果没有正确使用,我会很感激评论。
答案 0 :(得分:0)
你有几个问题。你正在使用&amp;而不是&amp;&amp; (并没有真正影响它,但仍然是错误的)你的指针错了指针。我更改了输出以显示存储在矩阵中的内容,而不是读取行。
*B[i][j]= ia;
必须为(*B)[i][j]= ia;
// Reading Matrix
f = fopen("matrix.txt", "r");
i=0;
while((read = getline(&line, &len, f)) != -1) {
pch = strtok(line," ,.-");
j=0;
while (pch != NULL && j<nmatrix){
printf("\n%d %d :", i, j);
ia= (int)*pch-48;
(*B)[i][j]= ia;
printf("%d\n", (*B)[i][j]);
pch = strtok(NULL," ,.-");
j=j+1;
}
i=i+1;
}
fclose(f);
答案 1 :(得分:-1)
你有很多错误:
你应该用“”初始化字符串行,而不是null。
int main(){
FILE *f;
int nmatrix=3;
int nmax=3;
int number, count, count2, i, j;
srand(time(NULL));
size_t len = 0;
ssize_t read;
char * line = "";
char * pch;
int ia;
int (*B)[nmatrix][nmatrix] = malloc(nmatrix * nmatrix * sizeof(int));
while(nmatrix<=nmax){
// Creation of Matrix
f = fopen("matrix.txt", "w");
for(count = 0; count < nmatrix; count ++){
for(count2 = 0; count2 < nmatrix; count2 ++){
number = rand()%9;
fprintf(f, "%s%d ", " ", number);
}
fprintf(f, "%s\n", " ");
}
fclose(f);
// Reading Matrix
f = fopen("matrix.txt", "r");
i=0;
while((read = getline(&line, &len, f)) != -1) {
printf("%s\n", line);
pch = strtok(line," ");
j=0;
while (pch != NULL && j < nmatrix){
ia= (int)*pch-48;
*B[i][j]= ia;
pch = strtok(NULL, " ");
j=j+1;
}
i=i+1;
}
fclose(f);
nmatrix=nmatrix+1;
}
return 0;
}