2013-03-02 52 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#ifdef _MSC_VER 
#include <crtdbg.h> // needed to check for memory leaks (Windows only!) 
#endif 

#define FLUSH while(getchar() != '\n') 

// Prototype Declarations 
int readFile(FILE* ifp,char** words); 

int main (void) 
{ 
// Local Definitions 
FILE *ifp; 
FILE *ofp; 
char fnamer[100]=""; 
char **words; 
int *freq; 
int i; 
int numWords =0; 

// Statements 

    words = (char**)calloc (1001, sizeof(int)); 
     if(words == NULL) 
     { 
      printf("Error with Calloc\n"); 
      exit(111); 
     } 


    if (!(ifp=fopen("/Users/r3spectak/Desktop/song_row.txt", "r"))) 
    { 
     printf("sucks"); 
     exit(100); 
    } 

    numWords = readFile(ifp,words); 

    printf("%d", numWords); 

    for(i=0;i<numWords;i++) 
    printf("\n%s",words[i]); 

    #ifdef _MSC_VER 
    printf(_CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n"); 
    #endif 
    printf("\n\t\tEnd of Program\n"); 
    printf("\n\t\tHave a great day!\n"); 
    return 0; 

} 


/*===============readFile================= 
Pre: 
Post: 
This function 
*/ 

int readFile(FILE* ifp,char** words) 
{ 

// Local Variables 
char buffer[1000] = " "; 
int numWords = 0; 

// Statements 
while (fscanf(ifp," %s",buffer)!=EOF) 
    { 
    words[numWords] = (char*)calloc(strlen(buffer)+1,sizeof(char)); 
       if(words[numWords] == NULL) 
       { 
        printf("\n"); 
        exit(111); 
       } 
       strcpy(words[numWords],buffer); 
       numWords++ ; 
    } 

return numWords; 

} 

輸入文件包含以下內容: 划船曲, 輕輕地往下流。 歡樂地,愉快地,愉快地, 生活不過是一場夢。如何通過省略它們%讀取用逗號串[^,]不是爲我工作

的fscanf後,我的陣列打印

Row, 
    row, 
    row 
    your 
    boat, and so on 

我要的是,

Row 
row 
row 
your 
boat 

我已經試過%[^ ,. \ n]和它不是爲​​我工作。它打印垃圾

+0

那麼你想逗號分隔輸入字符串? – 2013-03-02 06:22:10

+0

您不需要在C程序中強制使用'calloc()'的返回值。 – 2013-03-02 06:22:59

+0

@ H2CO3 im試圖不讀取逗號。 – 2013-03-02 06:25:09

回答

0

你可能會發現this函數特別有用。它會將您的字符串拆分爲令牌,如split()explode()的C等價物。

實施例:

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

int main(){ 
    char str[] ="Row, row, row your boat, Gently down the stream."; 
    char * pch; 
    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str," ,."); 
    while (pch != NULL){ 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " ,."); 
    } 
    return 0; 
} 

我基本上覆制了人頁的例子。再次使用第一個參數調用該函數爲NULL將調出下一個字符串標記。

相關問題