c - 为什么 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 会这样!
解决方案
temp_code
缓冲区不够大,无法读取字符串。这会导致您的程序具有未定义的行为。这就是为什么你会看到奇怪的无法解释的行为。
sizeof("student0002") == 12
因为在 C 字符串中需要一个空终止字符。
使temp_code
任何合理的输入足够大。例如char temp_code[2048];
,或研究防止缓冲区溢出的解决方案,如下所示:如何防止 scanf 在 C 中导致缓冲区溢出?
推荐阅读
- python - 我在 cmd 上运行 pytest,我得到了 AssertionError
- bash - 为什么我的命令不适用于 nohup 和 SSH?
- c++ - 如何在 C++ 中将类对象传递给另一个类成员数组
- python - 如何使用 numpy 广播创建 10 *10 时间表矩阵
- php - Laravel v8.15.0 (PHP v7.3.23) 共享服务器上的移动应用程序 API POST 路由不起作用
- angular - convert number to words in Angular
- python - 基于分隔符的python中的位置拆分数据帧
- pandas - 选择两个数据中的较高者
- c# - 如何添加 NuGet 仅源包依赖项
- java - Spring Boot jpa 不生成弹簧安全表“用户”和“权限”