2014-02-10 65 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); 
    } 
}