首页 > 解决方案 > 为什么 strcmp 在 C 编程中有时会在其输入字符串的末尾添加一个字符?

问题描述

在使用 Code::blocks 编写具有添加、删除、排序和搜索功能的学生列表的 C 编程作业中,我编写了一个基于学生代码搜索学生的函数,如下所示:

void search_student(struct student students[],int n)
{
    char temp_code[11];
    int row = 0;
    printf("Please enter the student code to search: ");
    scanf ("%s", temp_code);
    printf("\n#\tFirst_Name\tLast_Name\tStudent_Code\tAverage\n");
    puts("------------------------------------------------------------------");
    for (int i = 0 ; i < n ; i++)
    {
        printf("temp code= %s  --- students[%d].first_name = %s\n", temp_code, i, students[i].student_code);
        if (strcmp(temp_code, students[i].student_code) == 0 )
        {
            printf("%d\t%s\t\t%s\t\t%s\t%f\n",
                i+1, students[i].first_name, students[i].last_named, students[i].student_code, students[i].average);
            row = i + 1;
        }
    }
    if (row == 0)
    {
        puts("\nThe Student Code does not exist!\n");
    }
}

for 循环中第一个 fprint 的输出显示以下输出:

Please enter the student code to search: student0002

#       First_Name      Last_Name       Student_Code    Average
------------------------------------------------------------------
temp code= student0002  --- students[0].student_code = student0001
temp code= student0002  --- students[1].student_code = student0002
temp code= student0002  --- students[2].student_code = student0003

The Student Code does not exist!

似乎在第一个循环之后,strcmp 在 temp_code 的末尾添加了一个字符,导致输出错误!!!

我发现操纵不相关的代码部分可以解决这个问题!!(例如在 for 循环中的第二个 printf 之后删除 row = i+1 )当然使用 strncmp 可以很好地工作!无论如何,我无法弄清楚为什么 strcmp 会这样!

标签: c

解决方案


temp_code缓冲区不够大,无法读取字符串。这会导致您的程序具有未定义的行为。这就是为什么你会看到奇怪的无法解释的行为。

sizeof("student0002") == 12因为在 C 字符串中需要一个空终止字符。

使temp_code任何合理的输入足够大。例如char temp_code[2048];,或研究防止缓冲区溢出的解决方案,如下所示:如何防止 scanf 在 C 中导致缓冲区溢出?


推荐阅读