【发布时间】: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(),这是唯一一个糟糕到被从标准中删除的功能。