2016-11-22 114 views
0

我是c编程的新手,我遇到了一个程序问题。我应该从文件中读取三个数组。我正在使用的文件是Temps.txt,下面是文件中的内容。从文件中读取两个数组

1   31   37 
2   26   24 
3   30   38 
4   33   25 

5   33   21 
6   29   28 
7   41   46 

此去一路下跌,直到左栏为31。我写的代码是

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

int main() 
{ 
    FILE *readfile; 
    int New_York[31]; 
    int Anchorage[31]; 
    int Dates[31]; 
    int i; 
    printf("Date New York Anchorage\n"); 
    if((readfile = fopen("Temps.txt", "r")) == NULL) 
    { 
     printf("The file Temps failed to open\n"); 
    } 
    else 
    { 
     for(i = 0; i < 31; i++) 
     { 
      fscanf(readfile, "%d, %d, %d", Dates + i, New_York + i, Anchorage + i); 
      printf("%d  %d  %d\n", *(Dates + i), *(New_York + i), *(Anchorage + i)); 
     } 
     if(fclose(readfile) == EOF) //close the file. 
     { 
      printf("The file failed to close.\n"); 
     } 
    } 

    return(0); 
} 

当我编译它,它运行和所有正在读取打印数据的日期数组,在另外两个数组中,我获得了非常大的负数和正数。如果你可以请帮助,我会很感激。

谢谢

+3

你'fscanf'格式字符串包含逗号。是那些在文件中,还是文件空间分隔(如您的示例数据所示)? – Mac

+0

对于空格分隔的数字,最好在'scanf'格式字符串中使用不分隔符:'“%d%d%d”'。 – Gene

回答

4

摆脱逗号:"%d, %d, %d"

fscanf(readfile, "%d %d %d", Dates + i, New_York + i, Anchorage + i); 
+0

它工作。非常感谢您的帮助和快速回复。 – VictorS