2014-10-03 83 views
2

串在我的代碼,我從文件中讀取逗號分隔值。我使用刪除功能來刪除逗號。我遇到問題的地方是遍歷字符串。我覺得我用來遍歷字符串的for循環是正確的,但我可能做了一些非常愚蠢的事情,因爲程序失敗了。那麼,我如何正確地迭代一個字符串呢?通過迭代用C

文件中的每一行都有類似的格式:

0000000000001110,1 

這裏是我的代碼:

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


void removeChar(char *str, char garbage); 

int main(){ 
    FILE *ifp; 
    char *mode = "r"; 
    ifp = fopen("in.csv", mode); 


    char* string; 

    int i, len; 
    while(fscanf(ifp, "%s", string)!=EOF){ 
     removeChar(string, ','); 
     printf("%s \n", string); //gives me correct output of string with no comma 
     len = strlen(string); 
     for(i=0; i<len; i++)  //where the error occurs 
      printf("%c", string[i]); 
    } 

    return 0; 
} 

void removeChar(char *str, char garbage) { 

    char *src, *dst; 
    for (src = dst = str; *src != '\0'; src++) { 
     *dst = *src; 
     if (*dst != garbage) dst++; 
    } 
    *dst = '\0'; 
} 
+0

你得到了什麼錯誤? – Haris 2014-10-03 07:08:31

+0

@haris實際上沒有錯誤,程序只是崩潰。 – Ybarra 2014-10-03 07:10:19

+0

我已經能夠使用相同的方法遍歷一個字符串,但在不同的程序中。我不知道這裏有什麼不同,導致錯誤。 – Ybarra 2014-10-03 07:12:08

回答

3

您已經定義string爲:

char* string; 

,但你有沒有在使用它從文件讀取數據之前爲它分配內存。這導致未定義的行爲。

建議:

  1. 使用數組。
  2. 使用fgets,而不是fscanf。由於您指定了要讀取的最大字符數,因此fgetsfscanf更安全。

這是main的更新版本。

int main(){ 
    FILE *ifp; 
    char *mode = "r"; 
    ifp = fopen("in.csv", mode); 

    // Use an array of char. 
    char string[1024]; 

    int i, len; 
    // Use fgets instead of fscanf. 
    while(fgets(string, 1024, ifp) != NULL) { 
     removeChar(string, ','); 
     printf("%s \n", string); //gives me correct output of string with no comma 
     len = strlen(string); 
     for(i=0; i<len; i++)  //where the error occurs 
      printf("%c", string[i]); 
    } 

    return 0; 
} 
1

在進行所述的fscanf之前提供有效的存儲器指針char* string;

否則,嘗試這樣

char string[1000]; //這串字符數組。

1

粘貼另一個解決方案。它可以在讀取大型CSV文件時過濾輸入字符,速度非常快。

#include<stdio.h> 

#define LINE_MAXLEN  (1024) 

static size_t 
readline(char *buff, FILE *fp) 
{ 
     register char c; 
     char *p = buff; 
     while ((c = fgetc(fp)) > 43) if (c > 47) *p++ = c; // ord(',') == 44 and ord('0') == 48 
     *p = 0; 
     return (p - buff); 
} 

int 
main(void) 
{ 
     char line[LINE_MAXLEN]; 
     FILE *fp; 

     if ((fp = fopen("in.csv", "r")) == NULL) 
       perror("Error opening file"); 

     while (readline(line, fp)) 
       printf("line=%s\n", line); 

     return (0); 
}