2016-11-09 94 views
2

嗨,我有这个文本文件,其中第二个和第三个字符的第一列是整数..但我无法读取和打印值correctley。无法正确打印txt文件

所以这个文件想读:

c 6 
o 4 3 
o 2 4 
o 3 2 
o 1 1 
o 3 3 

这里是代码:

#include <stdio.h> 
#include <stdlib.h> 

#define N 6 

int main (int argc, char *argv[]) 
{ 
    int i; 
    int M[N]; 
    int U[N]; 
    char c ; 
    FILE* fichier = NULL; 

    fichier = fopen("pb1.txt","r"); 

if(fichier!= NULL) 
    { 
    while(!feof(fichier)) 
    { 
    fscanf(fichier, "%c %d %d", &c, &M[i], &U[i]); 

    printf("%c %d %d \n", c, M[i],U[i]); 
    } 

    } 
} 

这是输出的样子

c 6 1472131424 
o 4 3 

4 3 
o 2 4 

2 4 
o 3 2 

3 2 
o 1 1 

1 1 
o 3 3 

3 3 

我没有线索为什么给我这个。谢谢

+1

欢迎堆栈溢出!请参阅[为什么“while(!feof(file))”总是出错?](http://stackoverflow.com/q/5431941/2173917) –

回答

1

我在这里看到的第一个问题是,你使用未初始化的值i。它调用undefined behavior

详细说明,i是一个自动局部变量,除非明确初始化,否则将具有不确定的值。尝试使用这将导致UB。

此外,您从未增加i的值,该值应该用作存储和打印值的索引。

最后,在尝试使用扫描值之前,请务必检查返回值scanf()和家人以确保成功。

这就是说,请参阅Why is “while (!feof (file))” always wrong?