2013-03-04 1 views
0

오류 (100 자리, 1500 자리), 호환되지 않는 유형 내가 많은 수의 합을 찾기 위해 노력하고있어

내 SUM 함수가된다.

char *find_sum(char *a, char *b) { 
    char *res; 
    int alen, blen, rlen; 
    int carry; 

    alen = strlen(a); 
    blen = strlen(b); 
    rlen = 1 + ((alen > blen) ? alen : blen); 
    res = malloc(1 + rlen); 
    if (res) { 
    int oldlen = rlen; 
    res[rlen] = 0; 
    carry = 0; 
    while (rlen) { 
     int tmp; 
     if (alen && blen) tmp = a[--alen] - '0' + b[--blen] - '0'; 
     else if (alen) tmp = a[--alen] - '0'; 
     else if (blen) tmp = b[--blen] - '0'; 
     else tmp = 0; 
     tmp += carry; 
     res[--rlen] = '0' + tmp % 10; 
     carry = tmp/10; 
    } 
    if (res[0] == '0') memmove(res, res+1, oldlen); 
    } 
    return res; 
} 
내 data.txt로 아래가 예를 .FOR

char a[] = "243432423423423"; 
char b[] = "74356348775345"; 
char *c; 
c = find_sum(a,b); 
printf("%s",c); 

그러나 나는이 번호에 원하는 (A와 B) (선으로) 파일에서 얻을 : 나는 아래처럼하려고 해요 경우

, 코드가 작동됩니다 줄 :

내가 는 fgets을 사용하여 파일에서 추가 값으로하려고하면

210

7326473264723672364723864762374236 
32473264623748632784632784 
432423432423423423 
0 
3248972389473289473289478923 
4897238473247382 
732468723647236478238423 
0 
432748932489327894723894798239 
48327489237483278 
0 
32423423423423 

내가,이 파일을 열 모든 숫자의 각 라인과 합을 읽을 수 (다른 파일 sum.txt을 0에 도달 작성하는 경우 정지) , 호환되지 않는 형식 오류가 발생합니다.

내 테스트 코드 :

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

char *find_sum(char *a, char *b); 

int main(int argc, const char *argv[]) 
{ 
    FILE *file; 
    file = fopen("a.txt", "r"); 

    if (file != NULL){ 
     char *buf; 
     char *buf1; 
    char *sum; 
     fgets(buf, 100, file); 
     fgets(buf1, 100, file); 

     sum = find_sum(buf, buf1); 

     printf("%s",sum); 

    } 
    fclose(file); 

    return 0; 
} 
char *find_sum(char *a, char *b) { 
    char *res; 
    int alen, blen, rlen; 
    int carry; 

    alen = strlen(a); 
    blen = strlen(b); 
    rlen = 1 + ((alen > blen) ? alen : blen); 
    res = malloc(1 + rlen); 
    if (res) { 
    int oldlen = rlen; 
    res[rlen] = 0; 
    carry = 0; 
    while (rlen) { 
     int tmp; 
     if (alen && blen) tmp = a[--alen] - '0' + b[--blen] - '0'; 
     else if (alen) tmp = a[--alen] - '0'; 
     else if (blen) tmp = b[--blen] - '0'; 
     else tmp = 0; 
     tmp += carry; 
     res[--rlen] = '0' + tmp % 10; 
     carry = tmp/10; 
    } 
    if (res[0] == '0') memmove(res, res+1, oldlen); 
    } 
    return res; 
} 
+1

는 일반적으로 실제로하는 데 도움이 최초의 솔루션에 대한 샘플 구현 문제의 게시물을 게시 코드의 – cnicutar

+1

우리가 당신의 문제를 해결하기를 원한다면 일하고있는 코드를 게시하는 것이 그렇게 도움이되지 않습니다. – Hogan

+0

코드의 마녀 줄에 내 코드 –

답변

1

로 선언하는 것 당신은 메모리를 할당하고있는 마녀를 위해 타입에 던지십시오. 이 오류를 없애려면 고양이를 이렇게 추가하십시오.

res = (char*) malloc(1 + rlen); 

코드가 컴파일됩니다.

편집

읽기 파일에서 숫자와 루프에서 그에게 필요한 다른 출력 파일 기본적으로

에 추가의 결과를 쓰기는 두 개의 피연산자를 읽고 당신이 갖고 있기 때문에, 추가합니다 "0"이 포함 된 행을 찾았거나 EOF에 도달 한 경우에만 다음 루프에서 다음 피연산자를 읽고 이전 루프의 합계를 더한 다음 결과를 합계에 다시 저장해야합니다. "0" 또는 EOF에 도달 한 후 파일 합계를 출력 파일에 씁니다.

또 다른 대안은 "0" 또는 EOF에 도달 할 때까지 모든 숫자를 문자열 배열로 읽는 것입니다. 다음 단계에서는 모든 숫자를 반복하여 합계를 계산 한 다음 결과를 출력합니다 파일.여기

는 컴파일러 오류가있는 경우

int main(int argc, const char *argv[]) 
{ 
    char buf[100] = "";  
    FILE *input_file = fopen("a.txt", "r"); 

    if (input_file) { 
     FILE *output_file = fopen("r.txt", "w"); 
     if(output_file) { 
      char *op1 = NULL, *op2 = NULL, *sum = NULL, *p_buf = NULL; 

      do { 
       // if we alredy have done an additin, copy (flat) that result to op1 
       if(sum) { 
        printf("have sum %s\n", sum); 
        op1 = sum; 
       } 
       // if op1 does not point to a sum from previous addition, then attemp to read it from file 
       if(! op1) { 
        // read next operand and escape all "0" 
        do { 
         p_buf = fgets(buf, 100, input_file); 
         remove_new_line_ending(p_buf, buf); 
        } while(p_buf && 0 == strcmp(p_buf, "0")); 

        if(p_buf) { 
         printf("read op1 %s\n", buf); 
         op1 = strdup(buf); 
         sum = op1; 
        } 
       } 

       // read next operand 
       p_buf = fgets(buf, 100, input_file); 
       remove_new_line_ending(p_buf, buf); 
       if(p_buf && 0 != strcmp(p_buf, "0")) { 
        printf("read op2 %s\n", buf); 
        op2 = strdup(buf); 
       } 

       // we have both op1 and op2 then make the addition 
       if(op1 && op2) { 
        printf("have op1 and op2 %s\n", ""); 
        sum = find_sum(op1, op2); 
       } else { 
        if(sum) { 
         // if we have only op1 then it is the result from the previous addion and there is no operand left in the file 
         // then write the result to output file and reset all variables 
         printf("print sum %s to output file\n\n", sum); 
         fprintf(output_file, "%s\n0\n", sum); 
         free(sum); 
         sum = NULL; 
        } 
       } 
       free(op1); 
       free(op2); 
       op1 = NULL; 
       op2 = NULL; 

      } while(p_buf); 

      fclose(output_file); 

     } else { 
      perror("r.txt"); 
     } 

     fclose(input_file); 
    } else { 
     perror("a.txt"); 
    } 

    return 0; 
} 

void remove_new_line_ending(char* line, char dest[]) 
{ 
    if(line) { 
     int len = strlen(line); 
     int i = 0; 
     while(i < len && line[i] != '\r' && line[i] != '\n') { 
      dest[i] = line[i]; 
      i++; 
     } 
     dest[i] = '\0'; 
    } 
} 

입력

0 
0 
7326473264723672364723864762374236 
32473264623748632784632784 
432423432423423423 
0 
0 
0 
3248972389473289473289478923 
4897238473247382 
732468723647236478238423 
0 
0 
432748932489327894723894798239 
48327489237483278 
0 
32423423423423 
0 
0 

가 출력

7326473297196937420895929970430443 
0 
3249704858201833948240964728 
0 
432748932489376222213132281517 
0 
32423423423423 
0 
+0

char * num1 = malloc (100); char * num2 = malloc (100); char * sum = malloc (100); fgets (num1, 100, file); fgets (num2, 100, file); sum = find_sum (num1, num2); 합계가 잘못된 값을 반환합니다. –

+0

아마도 fgets가 "321312 \ n"을 반환합니까? –

+0

예'fgets()'는 문자열의 끝에 char/char-sequence라는 끝 문자를 저장합니다. widnows의 경우 줄 끝은'\ r \ n '이 될 수 있습니다. – A4L

0

당신은 주요 기능 (안 조건부 내부)의 시작 부분에 당신의 변수를 선언해야하며, 그들에게 메모리를 할당해야합니다. 이 작업을 수행하는 가장 쉬운 방법은 당신이

res = malloc(1 + rlen); 

malloc 반환에게 줄 요 필요 void* 마녀이 오류

36 D:\Projects\c_c++\so\find_sum\main.cpp invalid conversion from `void*' to `char*' 

을 gettign하는 gess

int main(int argc, const char *argv[]) 
{ 
    char buf[100]; 
    char buf1[100]; 
+0

'if (file) {...}'안에 왜 없습니까? 파일이 없으면 어떻게 될까요? 'fopen()'이 NULL을 반환 했습니까? 메모리는 무료로 할당됩니다! 좋은 연습은 변수를 필요로하기 바로 전에 변수에 메모리를 할당하는 것입니다. – A4L