2014-02-10 15 views
-1

我正在嘗試將幾個字符串讀入函數進行處理。這些指令將每個字符串傳遞給函數(不創建2d字符串數組)。參數必須保持不變。這是我試過的將多個字符串傳遞給函數

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

void convert(char s[]), int counts[]); 

int main(void) 
{ 
    int i = 0; 
    int d[2] = {}; 
    char text0[] = "this IS a String 4 you."; 
    char text1[] = "This sample has less than 987654321 leTTers."; 
    while(i<2) 
    { 
     convert (text[i],d); """ this is wrong but i dont know how to correctly do this 
     i = i +1; 
    } 

} 

void convert(char s[]), int counts[]) 
{ 

printf("%s this should print text1 and text2", s); 

} 

所以我有幾個問題。是否有某種特殊字符/運算符類似於python中的glob模塊,它可以正確地爲我執行convert (text[i],d)部分,我嘗試在每個字符串中進行讀取。此外,int counts[]的目的是填寫功能中的字和字符數。所以,如果我填補了這一陣列在功能convert將主也認識它,因爲我需要打印在main字/字符計數,而在convert

+0

'text0'和'text [0]'是完全不同的變量。 –

+0

是啊,那就是我卡住了。我想做這樣的事情,但我不知道如何 –

回答

0

返回實際計數我覺得你失去了「(」中的「無效轉換(char s []),int counts []);「。 它應該是void convert((char s []),int counts []);

+1

你不是一個答案,這樣的建議必須作爲評論給用戶的職位。 –

+0

@MadHatter也許他的聲譽得分不允許他發表評論http://stackoverflow.com/help/privileges/comment – nodakai

+0

@nodakai:對!!沒有注意到... –

1

您可以使用臨時字符串指針數組來傳遞的所有字符串:

char text1[] = "This sample has less than 987654321 leTTers."; 
    char const * texts[] = { text0, text1 }; 
    convert (texts, 2, d); 
} 

void convert(char const * s[], size_t n, int counts[]) 
{ 
    while(n--) { 
     *counts++ = strlen(*s); 
     printf("%s\n", *s++); 
    } 
} 

一些注意事項:

  1. 我加char const到函數參數類型。當函數不改變字符串時,你應該總是這樣做。如果您需要更改函數中的字符串,只需刪除const即可。
  2. 有額外的參數size_t n傳遞數組元素數到函數。 size_t可以在stddef.h中找到。
0
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

void convert(char s[], int counts[]); 

int main(void){ 
    int i = 0; 
    int d[2] = {0}; 
    char text0[] = "this IS a String 4 you."; 
    char text1[] = "This sample has less than 987654321 leTTers."; 
    char *text[] = { text0, text1 }; 
    for(i=0; i<2; ++i){ 
     convert (text[i], d); 
     printf("%d, %d\n", d[0], d[1]); 
    } 

} 

void convert(char s[], int counts[]){ 
    printf("%s\n", s); 
    { 
     char *temp = strdup(s); 
     char *word, *delimiter = " \t\n";//Word that are separated by space character. 
     int count_w=0, max_len=0; 
     for(word = strtok(temp, delimiter); word ; word = strtok(NULL, delimiter)){ 
      int len = strlen(word); 
      if(max_len < len) 
       max_len = len; 
      ++count_w; 
     } 
     counts[0] = count_w; 
     counts[1] = max_len; 
     free(temp); 
    } 
}