c - 为什么 strcmp 在 C 编程中有时会在其输入字符串的末尾添加一个字符?

标签 c

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

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 会这样!!

最佳答案

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

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

使 temp_code 足够大以进行任何合理的输入。例如。 char temp_code[2048]; 或研究防止缓冲区溢出的解决方案,如下所示:How to prevent scanf causing a buffer overflow in C?

关于c - 为什么 strcmp 在 C 编程中有时会在其输入字符串的末尾添加一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882645/

相关文章:

c - AES_128_CBC 使用 OpenSSL 加密/解密

c - C 的参数行选项解析

c - 为什么我的并行代码比顺序代码慢?

c++ - 如何使用 Windows API 确定注册表值数据的大小?

c - 如何在 HDF5 中写入固定长度的字符串?

c - Microsoft Visual C++ 运行时检查失败#2

c++ - 问题 : "error LNK2019: unresolved external symbol"

C exit() 函数 - 它的作用是什么?

c - 冒泡排序 C - 链表

c - 在 C 中的 pthread_join 之后出现段错误(核心已转储)