【问题标题】:Why is scanf causing infinite forlool [duplicate]为什么scanf会导致无限forloop [重复]
【发布时间】:2020-09-23 06:55:29
【问题描述】:

我刚开始 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]);
}

}

【问题讨论】:

  • 这能回答你的问题吗? scanf causing infinite loop in C
  • 始终检查scanf() 的返回值是否有错误。并且永远不要使用gets(),这是唯一一个糟糕到被从标准中删除的功能。

标签: c loops for-loop scanf


【解决方案1】:

由于某种原因,scanf() 将循环计数器 i 保持为 0。

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

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

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

C 是一种功能强大的语言,它允许您做任何事情,甚至可以自己动手。您在代码中编写的每一行都必须小心!

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多