2016-12-16 87 views
-1

我對編碼非常陌生,並且在打開文件時遇到了一些困難。我做了一些基本的文件,其中的數字,所有詮釋用c讀取文本文件

下面是該文件的例子:

20 
110 
1 0 1 5 
5 6 7 8 

這裏是我寫的讀它的代碼:

int* init_dados(char *name, int *n, int *iter){ 
FILE *f; 
int *p, *q; 
int i, j; 

f=fopen(name, "r"); 
if(!f) 
{ 
    printf("Error on the access of the file\n"); 
    exit(1); 
} 
// number of iteractions 
fscanf(f, " %d", iter); 
// number of vertices 
fscanf(f, " %d", n); 

p = malloc(sizeof(int)*(*n)*(*n)); 
if(!p) 
{ 
    printf("Error on the allocation of the memory\n"); 
    exit(1); 
} 
q=p; 

for(i=0; i<*n; i++) 
    for(j=0; j<*n; j++) 
     fscanf(f, " %d", q++); 
fclose(f); 
return p; 
} 

現在我有一個新的文件,它有像這樣int和漂浮:

1 2 7.83 
    1 3 -5.45 
    1 4 8.90 

我想讀取文本文件d還將其打印在屏幕上。我想也許我可以做最後一個節目,但我也有花車。我必須將它們保存在一個新的矢量中嗎?你會怎麼做?你可以幫我嗎?

+1

「110」頂點信息在哪裏?只有8個數字。然而,你的「新文件」可能需要讀入一個'struct',比如'struct indata {int a; int b; float f; };' –

+0

我投票結束這個問題作爲題外話,因爲這是一個「寫我的代碼」的問題,一個不好的例子。 –

+0

請更新問題。很難說出你真正想要的。 – RoadRunner

回答

0

您可以的fscanf使用%F的替代%d,當然你需要一個指針浮動可變

0

你可以嘗試在http://www.cplusplus.com/reference/cstdio/fscanf/

int data1; 
int data2; 
float data3; 

fscanf(f, "%d %d %e", data1, data2, data3); 

查找上的fscanf參考。

+0

考慮'int x; some_function(x);''x'沒有被初始化也沒有被賦值。 'some_function()'接受什麼值? 'x'沒有被定義也沒有被初始化,所以會導致問題。 'data1'也是這樣。 – chux