我试图从文件中读取数字。该文件具有以下格式:
2 4 5 7
3 2 4 7
我尝试使用fscanf
来收集新行的所有数字并将数字存储在数组中,并将数字存储在第二行中。但直接从第二行继续不再启动并将其存储在另一个数组中。是否可以使用fscanf
?
int main(void)
{
FILE* fp;
int *vec = malloc(sizeof(int)*6);
int *vec_2 = malloc(sizeof(int)*6);
int row, i;
fp = fopen("vector.txt","r");
for(i = 0; i < row; i++) //I don't know how to read until newline
fscanf(fp, "%d", &vec[k]); //here store the first row in the array
for(i = 0; i < row; i++)
fscanf(fp, "%d", &vec_2[i]); //start reading here from the second row
free(vec);
free(vec_2);
return 0;
}
答案 0 :(得分:1)
int main(void){
FILE* fp;
int cols = 6;
int *vec_1 = malloc(sizeof(int)*cols);
int *vec_2 = malloc(sizeof(int)*cols);
int i, i1, i2;
char ch;
fp = fopen("vector.txt","r");
for(i1 = 0; i1 < cols; ){
fscanf(fp, "%d%c", &vec_1[i1++], &ch);//Format is limited. "num[ \t\n]"
if(ch == '\n')
break;
}
i2 = 0;
while(1==fscanf(fp, "%d", &vec_2[i2])){
if(++i2 == cols)
break;
}
fclose(fp);
printf("first : ");
for(i=0; i<i1; ++i)
printf("%d ", vec_1[i]);
printf("\n");
printf("second : ");
for(i=0; i<i2; ++i)
printf("%d ", vec_2[i]);
printf("\n");
free(vec_1);
free(vec_2);
return 0;
}
答案 1 :(得分:0)
行必须初始化为6并且可能也是col,您可以使用以下二维数组。
int main()
{
FILE* fp;
int **vec;
int row = 6, col = 6, i, j;
vec = malloc(sizeof(int *)*row); // allocates space for each row
for (i = 0; i < row; i++) {
vec[i] = malloc(sizeof(int)*col); // now allocate space for each cell within a row
}
fp = fopen("vector.txt","r");
for(i = 0; i < row; i++) {
for (j=0; j < col; j++) {
fscanf(fp, "%d", &vec[i][j]); // read ith row, jth col
}
}
vec = malloc(sizeof(int *)*row);
for (i = 0; i < row; i++) {
free(vec[i]);
}
free(vec);
return 0;
}
答案 2 :(得分:0)
任何时候数据都存储在行中,最好考虑fgets()
。
此解决方案适用于N行和用户可选择的列宽
#define MAX_INT_WIDTH (sizeof (int) * CHAR_BIT/3 + 3)
int **Read_Lines_Of_Numbers(FILE* inf, size_t Expected_Row_Width) {
int **Row = NULL;
size_t RowCount = 0;
size_t RowSize = 0;
char buf[Expected_Row_Width * (MAX_INT_WIDTH + 1) + 2];
while (fgets(buf, sizeof buf, inf) != NULL) {
if (RowCount >= RowSize) {
RowSize = (RowSize + 1) * 2; // Double size
Row = realloc(Row, RowSize * sizeof *Row); // OOM checking omitted
}
Row[RowCount] = calloc(Expected_Row_Width, sizeof *Row[RowCount]); // OOM checking omitted
size_t i;
char *p = buf;
for (i = 0; i < Expected_Row_Width; i++) {
int n;
if (sscanf(p, "%d %n", &Row[RowCount][i], &n) != 1)
break;
p += n;
}
if (*p || i != Expected_Row_Width) { // Bad data on line
free(Row);
return NULL;
}
RowCount++;
}
Row = realloc(Row, (RowCount + 1) * sizeof *Row); // OOM checking omitted
Row[RowCount] = NULL;
return Row;
}
int main(void) {
FILE *inf = fopen("c:/tmp/vector.txt", "r");
size_t Width = 4;
int **Data = Read_Lines_Of_Numbers(inf, Width);
fclose(inf);
if (Data) {
size_t i;
for (i = 0; Data[i]; i++) {
size_t j;
for (j = 0; j < Width; j++) {
printf(" %d", Data[i][j]);
}
fputc('\n', stdout);
}
free(Data);
}
return 0;
}