gpt4 book ai didi

C : Infinite loop when using scanf

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:59 29 4
gpt4 key购买 nike

我正在使用以下结构:

struct Transistor {
char type_number[50];
char supplier[50];
int maxVce;
float maxIc;
int max_power;
int max_freq;
int max_gain;
float price;
};

运行代码:

while(1==1){
printf("Insert parameters: \n");
char input[100];
scanf ("%[^\n]", &input);
char *token = strtok(input, " ");
if(input[0]=='q'){
return 0;
}
parameters[0]=atoi(token);
token = strtok(NULL, " ");
ic=atof(token);
token = strtok(NULL, " ");
parameters[1]=atoi(token);
token = strtok(NULL, " ");
parameters[2]=atoi (token);
token = strtok(NULL, " ");
parameters[3]=atoi(token);


printf ("\n Parameters: \nVCe:%d,\nPow:%d,\nFreq:%d,\nGain:%d \nIce:%.3f\n",parameters[0],parameters[1],parameters[2],parameters[3],ic);
printf("Transistor that matches your requirements: \n");
for(a=0; a<15; a++){
i=0;
if(parameters[0]<=all_Transistors[a].maxVce){
i++;
}
if(parameters[1]<=all_Transistors[a].max_power){
i++;
}
if(parameters[2]<=all_Transistors[a].max_freq){
i++;
}
if(parameters[3]<=all_Transistors[a].max_gain){
i++;
}
if(ic<=all_Transistors[a].maxIc) {
i++;
}
if(i==5){
printf("\n\nTransistor name: %s\n",all_Transistors[a].type_number);
printf("Supplier: %s\n",all_Transistors[a].supplier);
printf("Maximum Vce: %d\n",all_Transistors[a].maxVce);
printf("Maximum Ic: %.3f\n",all_Transistors[a].maxIc);
printf("Maximum power: %d\n",all_Transistors[a].max_power);
printf("Maximum freq: %d\n",all_Transistors[a].max_freq);
printf("Maximum gain: %d\n",all_Transistors[a].max_gain);
printf("Price: %.3f\n",all_Transistors[a].price);
}
}
}

事情是:我正在输入第一组参数,例如:

1 1.1 2 3 4

它可以很好地循环运行,但 scanf 不是,只要用户输入 q 作为输入的第一个字符,它就应该可以工作。

为什么 scanf 没有运行每个循环?

最佳答案

这条线的主要问题:

scanf ("%[^\n]", &input);

是它读取从 stdin 缓冲区到 '\n' 的所有内容 并在 '\n' 中留下缓冲区。因此,下次您返回到该行以从缓冲区中读取时,缓冲区中的第一个字符仍然是 '\n',导致没有任何内容被读取并且缓冲区没有被更改。

(该行的另一个问题是,如果正在读取的行比input 数组长,则存在缓冲区溢出的风险)。

解决这个问题的方法不止一种,但最简单的方法(也应该保护您免受缓冲区溢出)是评论中提到的方法,使用 fgets(input, sizeof input,标准输入);

关于C : Infinite loop when using scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540903/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com