为什么 scanf 导致无限循环

Why is scanf causing infinite forlool

我刚开始使用 C,我不知道为什么会这样。当我执行程序时,它只在 service_code 数组中存储了 1 个值。出于某种原因,scanf() 将循环计数器 i 保持为 0。我找不到解决方案。 scanf() 导致 forloop 无限地 运行。有谁知道如何解决这个问题?

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

int main() {
    
char name [100];
char str [10];
int discount = 0 ;
int age;
char service_codes[4][6];


printf("Welcome to Nelson Lanka Hospital \n");
printf("Our Services : \n SV105 - Doctor Channeling \n SV156 - Pharmacy \n SV128 - Laboratory \n SV100 - OPD \n \n");

printf("Enter your Details \n Name : ");
scanf("%[^\n]",name);
printf(" Enter age : ");
scanf("%d",&age);



printf(" Enter the Sevice code for the service you need : ");
scanf("%s", str);
strcpy(service_codes[0], str);


for(int i = 1; i<4; i++){

    char yn [2] = "y";
    printf("Do you need any other sevices? (y/n) : ");
    gets(yn);
    if (strcmp(yn, "n")==0){
        break;
    }
    printf(" Enter the Sevice code for the service you need : ");
    scanf("%s", str);
    strcpy(service_codes[i], str);
    printf("%s \t %s \t %d \n",service_codes[i],str,i);

}


for (int x = 0; x<4; x++){
    printf("%s \n",service_codes[x]);
}

}

For some reason, the scanf() is keeping the loop counter i as 0.

您可能遇到了缓冲区溢出,它正在改变堆栈中的变量(例如变量 i)。我在您的程序中至少看到两个可能发生缓冲区溢出的地方:

  • scanf("%s", str);:数组 str 只能容纳 9 个字符(加上 1 个用作字符串终止符的结束空字符)。如果您输入的字符串超过 9 个字符(包括换行符和回车符 return 后附加的字符),那么 scanf 将损坏堆栈。

  • strcpy(service_codes[i], str);:数组 service_codes 中的每个元素都定义为每个元素有 6 个字节(5 个字符的空间加上 1 个结束空终止符)。通过复制这样的字符串,其中 str 可能比 service_code 长,您将 运行 进入缓冲区溢出。

C 是一种功能强大的语言,可以让您做任何事情,甚至是自取其辱。您在代码中写的每一行都必须小心!