美好的一天!多个输入C
我试图创建一个函数,获取多个输入的电阻值。在我的主要功能中,程序要求用户询问需要多少个电阻。用户需要的电阻数量将成为程序要求用户输入电阻值的次数。问题是我应该使用什么循环来创建错误语句,并让用户再次输入值。输入只接受整数。这里是代码:
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 500
int resistors(int rescount, int *val_res);
int validate (char *a)
{
unsigned x;
for (x = 0; x < strlen (a); x++)
if (!isdigit (a[x]))
return 1;
return 0;
}
int main()
{
int numres;
int resistance[MAXSIZE];
char resist[MAXSIZE];
do
{
printf("How many resistors do you want to place in the circuit?\n");
if (fgets(resist, sizeof(resist), stdin) != NULL)
{
resist[strlen (resist) - 1] = '\0';
if(validate (resist) == 0)
{
numres = atoi(resist);
}
}
} while(numres < 1 || numres > 100);
resistors(numres, resistance);
return 0;
}
int resistors(int rescount, int *val_res)
{
char resistor_value[MAXSIZE];
int z;
printf("Please input the value of resistors:\n");
for(z = 1; z < (*val_res); z++)
{
printf("\tPlease input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}
do{
printf("\tInvalid Resistance\n");
printf("\tRe-input Resistor #%d: \n", z);
if (fgets(resistor_value, sizeof(resistor_value), stdin) != NULL)
{
resistor_value[strlen (resistor_value) - 1] = '\0';
if(validate (resistor_value) == 0)
{
val_res[z-1] = atof(resistor_value);
}
}
}while(val_res[z-1] < 0);
}
}
输出应该是这样的:
多少电阻你要在电路的地方?
请输入电阻的值:
请输入电阻器#1:
ABCD
无效电阻!
重新输入电阻#1:
请输入电阻#2:
...
等
不发生在我的代码上。请帮忙谢谢!
你可以使用['strtol'(http://en.cppreference.com/w/c/string/byte/strtol)或['sscanf'(HTTP://en.cppreference。 COM/W/C/IO /的fscanf)。两者都可用于转换和验证字符串。 –
我已经完成验证部分。我的问题是如何循环说重新输入阻力的声明。 – JayCastillo
我只是说有更简单的方法来处理验证和转换。至于如何在验证失败时循环,没有“标准”的方式来做这件事,你可以使用任何你想要的循环,常见的是例如'while(scanf(resist,“%d”,&numres)!= 1){/ *不正确的输入,再试一次* /}' –