You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C语言大小写不敏感姓名搜索程序报错求助:函数与变量未声明问题

解决你的C代码编译错误及功能修正

咱们先来搞定你遇到的编译错误,然后再把代码里的其他小问题一并修正,让它能正常实现大小写不敏感的姓名搜索功能。

1. 核心编译错误的解决

你看到的Variable or field 'lowercase_words' declared void'str' was not declared in this scope错误,根源是函数参数没有指定类型:

void lowercase_words(str) {

在C语言里,必须明确声明函数参数的类型,编译器才能识别变量str是什么。咱们把函数定义改成这样:

void lowercase_words(char *str) {

这样就告诉编译器str是一个字符指针(对应字符串数组),编译错误就会消失。

2. 其他需要调整的代码问题

解决完上面的错误后,代码还有几个小问题会导致运行异常或者新的编译错误,咱们逐个修正:

  • 函数名不匹配:你定义的函数叫lowercase_words,但调用的时候写成了lowercase,比如lowercase(names[j]);lowercase(b[]);,要统一改成lowercase_words;另外lowercase(b[]);的写法错误,数组名本身就是指针,直接写lowercase_words(b);就行。
  • 多余无效变量:代码里的char str[];没有初始化,完全没用,直接删掉。
  • 循环越界+效率问题:原来的for(i=0;i<=strlen(str);i++)会访问到字符串结束符\0之后的内存(越界),而且每次循环都调用strlen效率很低。改成用while循环判断结束符更稳妥,同时用标准库的tolower函数转小写,比手动判断ASCII值兼容性更好:
    void lowercase_words(char *str) {
        int i = 0;
        while (str[i] != '\0') {
            str[i] = tolower((unsigned char)str[i]);
            i++;
        }
    }
    
  • printf格式符错误:你用了%[^\n]来输出字符串,这是scanf的专属格式符,printf里输出字符串要用%s,比如把printf("%[^\n] found in index-%d", b, i);改成printf("%s found in index-%d\n", b, i);
  • 输入处理优化:读取数字后的换行符,用getchar()scanf("%c", &ignore);更直接,避免漏读或多读空白字符。

修正后的完整代码

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void lowercase_words(char *str) {
    int i = 0;
    while (str[i] != '\0') {
        str[i] = tolower((unsigned char)str[i]);
        i++;
    }
}

int main() {
    int a;
    char b[255];
    int c = 0;
    printf("How many names do you want to input? ");
    scanf("%d", &a);
    getchar(); // 读取数字输入后的换行符

    char names[a][255]; // C99变长数组,现代编译器都支持
    int j;
    for(j = 0; j < a; j++){
        printf("Input name %d: ", j+1);
        scanf("%[^\n]", names[j]);
        lowercase_words(names[j]);
        getchar(); // 读取换行符,避免影响下一次输入
    }

    printf("Input the name you are searching: ");
    scanf("%[^\n]", b);
    lowercase_words(b);

    int i;
    for(i = 0; i < a; i++) {
        if(strcmp(b, names[i]) == 0) {
            c = 1;
            printf("%s found in index-%d\n", b, i);
            break;
        }
    }
    if (c == 0) {
        printf("We can't find %s\n", b);
    }
    return 0;
}

测试运行示例

How many names do you want to input? 3
Input name 1: John Harrow
Input name 2: Dean
Input name 3: Michael Jackson
Input the name you are searching: john harrOW
john harrow found in index-0

内容的提问来源于stack exchange,提问作者Rifky

火山引擎 最新活动