如何在 C 中的 for 循环内将“字符串用户输入”与“数组中的字符串列表”进行比较

问题描述 投票:0回答:1

我是 C 编程语言新手,正在尝试一些实践。 我想使用 for 循环将用户输入的字符串与数组中的字符串列表进行比较。我的代码看起来像这样:-

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

void converter();

int main() {
    
    converter();
    return 0;
}

void converter(){
    char convert[] = "";
    char store[] = "";
    int compare;
    char List[10][4] = {"ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX","YZA"};
    
    printf("Which one do you want to select : \n");
    
    for(int i=0 ; i<9 ; i++){
        printf("%s \n",List[i]);
        
    }
    
    printf("Please select One : ");
    scanf("%s",&convert);
    
    for (int j=0 ; j<9 ; j++) {
        printf("%d \n",strcmp(convert,List[j]));
        
        if (strcmp(convert,List[j]) == 0){
            compare = 1;
            break;
            
        }
        
    }
    
    if (compare != 1){
        printf("Sorry your selected itemm is not valid. Please enter a valid selection \n");
        converter();
    }
    
    printf("Ok we can proceed now");
    
}

运行代码后,我得到以下输出

output of the above code

即使用户输入的字符串与列表中的字符串相同,strcmp() 也不会输出 0。 但我观察到的另一件事是,如果我只是注释掉 for 循环内的 if 条件,那么 strcmp() 将给出 printf 打印的输出 0 。

注释 if 函数后的代码:-

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

void converter();

int main() {
    
    converter();
    return 0;
}

void converter(){
    char convert[] = "";
    char store[] = "";
    int compare;
    char List[10][4] = {"ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX","YZA"};
    
    printf("Which one do you want to select : \n");
    
    for(int i=0 ; i<9 ; i++){
        printf("%s \n",List[i]);
        
    }
    
    printf("Please select One : ");
    scanf("%s",&convert);
    
    for (int j=0 ; j<9 ; j++) {
        printf("%d \n",strcmp(convert,List[j]));
        
        //if (strcmp(convert,List[j]) == 0){
        //    compare = 1;
        //    break;
            
        //}
        
    }
    
    if (compare != 1){
        printf("Sorry your selected itemm is not valid. Please enter a valid selection \n");
        converter();
    }
    
    printf("Ok we can proceed now");
    
}

输出:- output after commenting

所以,我无法比较数组列表中的用户输入。

我想从代码中实现什么:-

用户将使用 for 循环显示字符串数组中的所有项目。然后,用户将从显示的列表中输入一个字符串,然后代码将使用 for 循环将输入字符串与该数组中已定义的字符串进行比较。 如果用户输入的字符串与数组中的任何字符串匹配,那么我们可以继续执行下一部分代码,否则将重复该函数,再次要求用户输入字符串,直到并且除非它与数组中的任何字符串匹配列在数组中。用户将始终知道他/她正在输入什么,因为我们首先显示列表项,然后要求从中选择一次。

请帮助我找到一个解决方案,将用户输入作为字符串进行比较,并将其与字符串数组列表进行比较。

也让我知道我哪里做错了。

提前感谢您的帮助。

arrays c loops scanf strcmp
1个回答
3
投票

此代码是未定义的行为:

char convert[] = "";
scanf("%s",&convert);

convert
的大小为1个字符(空终止符)。所以里面绝对没有空间可以存储任何文本。

您需要将任何字符串的最大缓冲区大小传递给

scanf()
,并且需要检查
scanf()
的返回值。

如果您使用这些工具构建程序,则会自动检测到此错误和其他类似错误:

© www.soinside.com 2019 - 2024. All rights reserved.