2012-07-05 4 views
0

i가 입력 파일을 가지고 실제로 내가 필요한 얼굴 가변 약 2 스택을 실행 데 따라서 위의 예에서 파일을 더 많이 읽으십시오. (사이에 공백이 없으므로 배열의 크기를 텍스트 파일의 행에 따라 달라야합니다.)이 코드는 내가 사용하는 방법입니다.시간 검사 실패 번호를 <p> <p>8</p> <p>10</p></p> <p>5</p> 아래와 같이 "숫자"

#include "stdafx.h" 
#include <ctype.h> 
#include <string.h> 
#include <stdlib.h> 
#include <stdio.h> 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    FILE *test; 
    int numbers[]={0}; 
    int i=0; 
    char *array1; 
    if((test=fopen("Input1.txt","r"))==NULL) 
    { 
     printf("File could not be opened\n"); 
    } 
    else 
    { 
     array1 = (char*)malloc(1000*sizeof (char)); 
     if((test=fopen("Input1.txt","r"))==NULL) 
     { 
      printf("File could not be opened\n"); 
     } 
     else 
     { 
      while(fgets(array1,(sizeof array1)-1,test)!=NULL) 
      { 
       numbers[i]=atoi(array1); 
       i++; 
      } 
      for(i=0;i<sizeof(array1)-1;i++) 
      { 
       printf("%d\n",numbers[i]); 
      } 
     } 
    fclose (test); 
    } 
    system("pause"); 
    return 0; 
    free(array1); 
} 
+0

만약 소자 numbers' '의 정의에서 누락 카운트 (예를 들어'번호 [1000] '). – reuben

+0

하지만 텍스트 크기에 따라 다를 수 있습니다. 내가 가진 것보다 더 큰 텍스트 크기가 있다면, 또한 오류가 발생합니다. – user1502809

+1

@ user15020809 그래, 그래서 ... 동적으로 할당하십시오. 필요한 경우 고정 길이로 시작하십시오. 'realloc'을 사용하여 언제든지 나중에 확장 할 수 있습니다. – reuben

답변

0

sizeof을 사용하면 할 수없는 일을하고 있습니다.
sizeof array1은 변수 array1의 크기입니다. char *으로 정의 되었기 때문에 크기는 포인터의 크기입니다 (32 비트 시스템에서는 4 개, 64 비트에서 8 개).
분명히 할당 된 메모리 양이 array1 인 것을 원합니다. 그러나 sizeof는 그것을 줄 수 없습니다.

귀하의 경우 1000의 배정액 크기를 사용해야합니다. 두 자리에서 숫자 1000을 사용하는 대신 변수에 넣는 것이 더 좋습니다 (하나를 변경하면 다른 것을 변경하는 것을 잊을 수 있기 때문입니다).

0

예컨대

{ 
    FILE *test; 
    int *numbers=NULL; 
    int i=0,size=0; 
    char array1[1000];//don't need dynamic allocate 

    if((test=fopen("Input1.txt","r"))==NULL) 
    { 
     printf("File could not be opened\n"); 
    } 
    else 
    { 
     while(fgets(array1, sizeof(array1), test)!=NULL) 
     { 
      numbers=(int*)realloc(numbers,sizeof(int)*(i+1)); 
      numbers[i++]=atoi(array1); 
     } 
     size=i; 
     for(i=0;i<size;i++) 
     { 
      printf("%d\n",numbers[i]); 
     } 
     fclose(test); 
     free(numbers); 
    } 
    system("pause"); 
    return 0; 
}