dor*_*kce 1 c function default-parameters
我正在尝试在C中创建一个indexOf函数.该函数必须找到参数中给出的任何字母或单词的位置.但是当我试图使用它们时,编译器会警告"参数太少".我怎样才能做到这一点?谢谢.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int indexOf(char*, char*, char);
int main(){
char stuff[] = "abcdefghijklmopqrstuvwxyz";
printf("Result: %d", indexOf(stuff, 'b') );
printf("Result: %d", indexOf(stuff, "defg") );
getch();
return 0;
}
int indexOf(char *text, char *word, char letter){
if(word == DEFAULT VALUE)
// find the letter in the text
else if(letter == DEFAULT VALUE)
// find the word in the text
}
Run Code Online (Sandbox Code Playgroud)
您无法在C中执行此操作:该语言不支持重载或默认参数.你可以做的唯一一件事就是使用可变数量的参数,但这在这里不起作用,因为你需要传递一个额外的参数来指示被搜索项目的类型.
更好的方法是定义两个函数
int indexOfChar(char *text, char letter)
int indexOfWord(char *text, char *wors)
Run Code Online (Sandbox Code Playgroud)
或者更好的是,使用标准库中的相应功能 - strchr和strstr.