Physicaloser 2017-02-06 15:42 采纳率: 0%
浏览 1244

求教一个简单的C语言题目..

题目是:设计并测试一个函数,其功能是搜索由函数的第一个参数指定的字符串,在其中查找由函数的第二个参数指定的字符的第一次出现的位置。如果找到,返回指向这个字符的指针:如果没有找到,返回空字符(这种方式和 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;

}

当字符串中有该字符时,输出的结果完全正确,
但是当字符串中没有该字符时,就出现错误。
想了半天还是没看出来。。

  • 写回答

4条回答 默认 最新

  • threenewbee 2017-02-06 15:50
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误