题目是:设计并测试一个函数,其功能是搜索由函数的第一个参数指定的字符串,在其中查找由函数的第二个参数指定的字符的第一次出现的位置。如果找到,返回指向这个字符的指针:如果没有找到,返回空字符(这种方式和 strchr()函数的功能一样)。在一个使用循环语句为这个函数提供输入的完整程序中进行测试。
我的代码
#include
#include
#define QUIT "quit"
#define SIZE 80
//搜索字符在字符串中首次出现的位置
char * str_ch(char * str, char c);
int main(void)
{
char str[SIZE];
char ch;
char * ret_val;
printf("Input a string (type quit to quit):\n");
gets(str);
while (strcmp(str, QUIT))
{
printf("Input a character: ");
scanf("%c", &ch);
while (getchar() != '\n') //跳过剩余输入部分
continue;
ret_val = str_ch(str, ch);
if (ret_val != NULL)
printf("Find! The string start with the %c:\n"
"%s\n", ch, ret_val);
else
printf("Can't find!\n");
printf("Input a string (type quit to quit):\n");
gets(str);
}
printf("Bye.\n");
return 0;
}
char * str_ch(char * str, char c)
{
int flag = 0;
while (str)
if (*str++ == c)
{
flag = 1;
break;
}
if (flag)
return str - 1;
else
return NULL;
}
当字符串中有该字符时,输出的结果完全正确,
但是当字符串中没有该字符时,就出现错误。
想了半天还是没看出来。。