C中整数行的结尾 [英] The end of an integer line in C
问题描述
我必须从C语言的文本文件中读取一个未定义的矩阵,我想逐行读取它,这样每一行都是一个整数数组。但我怎么知道一行的结尾,因为我不能使用\ n作为字符?
以下是代码:
I have to read an undefined matrix from a text file in C language, and i want to read it line by line so that each line will be an integer array.But how do i know where is the end of a line, since i can't use "\n" as in for characters? Here is the code:
#include "stdafx.h"
#include "stdlib.h"
#include "stdio.h"
using namespace System;
typedef struct
{
int *v;
int n;
}vector;
int main(array<System::String ^> ^args)
{
vector *a;
FILE* f;
int n = 15;
int i = 0;
int j,k;
if ((f = fopen("C:\\Users\\Mirelaa\\Documents\\visual studio 2013\\Projects\\MatriceNedefinita\\MatriceNedefinita\\Debug\\fisier2.in", "rt")) == NULL)
{
printf("Fisierul nu poate fi deschis!");
exit(1);
};
a = (vector *)malloc(n * sizeof(vector));
while (!feof(f))
{
a[i].v = (int*)malloc(n * sizeof(int));
a[i].n = 0;
//citeste rand
//citesti fiecare element din rand
j = 0;
while (a[i].v[j] != '\0')// wrong!!
{
fscanf(f, "%d", &a[i].v[j]);
j++;
a[i].n = a[i].n + 1;
}
for (k = 0 ; k < a[i].n ; k++)
{
printf("%d", a[i].v[j]);
printf("\n");
}
i++;
if (i == n)
{
n = 2 * n;
a = (vector *)realloc(a, n * sizeof(vector));
a[i].v = (int *)realloc(a[i].v, n * sizeof(int));
}
}
return 0;
}
推荐答案
读取一行整数和保存在可变大小的数组中是一种方法。
Reading a line of integers and saving in a variable sized array is one approach.
fscanf的问题(f,%d,...
是它首先读取空格并且代码丢失了'\ n'
的出现。代码需要通过其他方式查找。
The trouble with fscanf(f, "%d",...
is that it first reads white-space and code loses the occurrence of '\n'
. Code needs to look for it by some other means.
但是不要打包 main()
中的所有代码,而应考虑辅助函数。在C函数之后读取一个行的数字并返回 NULL
on 1)内存不足,2)没有数据或转换失败而没有读取数字。否则返回 vector
。它不限于任何行长度。
But rather than pack all the code in main()
, consider helper functions. Following C function reads one line of numbers and return NULL
on 1) out-of-memory, 2) no data or conversion failure with no numbers read. Otherwise return vector
. It is not limited to any line length.
typedef struct {
int *v;
size_t n;
} vector;
vector *Read_vector(vector *v1, FILE *inf) {
v1->v = NULL;
v1->n = 0;
size_t size = 0;
for (;;) {
int number;
int ch;
// Check leading white-space for \n
while (isspace(ch = fgetc(inf))) {
if (ch == '\n') break;
}
if (ch == '\n' || ch == EOF) break;
ungetc(ch, inf);
if (1 != fscanf(inf, "%d", &number)) {
break;
}
// Is `v1` large enough?
if (v1.n >= size) {
size = size*2 + 1;
vector nu;
nu.v = realloc(v1->v, size * sizeof *nu.v);
if (nu.v == NULL) {
free(v1->v);
v1->v = NULL;
v1->n = 0;
return NULL;
}
v1->v = nu.v;
}
v1.v[v1.n++] = number;
}
if (v1->n == 0) {
return NULL;
}
return v1;
}
通过重复调用,可以获得一组向量。把它留给OP,因为它与上面的非常类似。
With repeated calls, an array of vectors could be had. Leave that to OP as it is very similar to the above.
注意:避免使用 while(!feof(f))
。
这篇关于C中整数行的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!