gpt4 book ai didi

c - 如何防止用户在c中输入0或负数

转载 作者:行者123 更新时间:2023-11-30 16:39:27 26 4
gpt4 key购买 nike

我写了这个函数:

float checkInput1(void){
float option1,check1;
char c;

do{
printf("Enter the first side of the triangle: ");

if(scanf("%f%c",&option1,&c) == 0 || c != '\n'){
while((check1 = getchar()) != 0 && check1 != '\n' && check1 != EOF);
printf("\t[ERR] Invalid number for the triplet.\n");
}else{
break;
}
}while(1);
return option1;
}

但是,为了阻止用户输入字母等,我想扩展此验证功能,使用户无法输入 0 或负数。我怎么做?提前致谢

最佳答案

考虑使用fgets进行输入并使用strtod进行解析。除非有特殊原因,否则请使用 double 而不是 float。使用最小值 -HUGE_VALF 和最大值 HUGE_VALF 会将 double 值限制为 float 范围。这使用 1.0e-10 的最小值来拒绝零和更小的值。有效的分隔符是"\n",但可以根据需要更改以允许逗号或其他分隔符。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <math.h>

int parse_double ( char *line, char **next, char *delim, double *value, double min, double max) {
char *end = NULL;
double input = 0.0;

errno = 0;
input = strtod ( line, &end);
if ( ( errno == ERANGE && ( input == HUGE_VAL || input == -HUGE_VAL))
|| ( errno != 0 && input == 0.0)){
perror ( "input: ");
return 0;// failure
}
if ( end == line) {
line[strcspn ( line, "\n")] = '\0';
printf ( "input [%s] MUST be a number\n", line);
return 0;// failure
}
if ( *end != '\0' && !( delim && ( strchr ( delim, *end)))) {// is *end '\0' or is *end in delim
line[strcspn ( line, "\n")] = '\0';//remove trailing newline
printf ( "problem with input: [%s] \n", line);
return 0;// failure
}
if ( next != NULL) {// if next is NULL, caller did not want pointer to end of parsed value
*next = end;// *next allows modification to caller's pointer
}
if ( input < min || input > max) {
printf ( "out of range\n");
return 0;// failure
}
if ( value != NULL) {// make sure value is not NULL
*value = input;// *value allows modification to callers double
}
return 1;// success
}

int read_double ( double *dValue) {
char line[900] = {'\0'};
int valid = 0;

*dValue = 0.0;
do {
printf ( "Enter a number or quit\n");
if ( fgets ( line, sizeof ( line), stdin)) {//read a line
if ( strcmp ( line, "quit\n") == 0) {
return 0;//exit when quit is entered
}
valid = parse_double ( line, NULL, "\n", dValue, 1.0e-10, HUGE_VALF);
}
else {
return 0;//fgets failed
}
} while ( !valid);

return 1;
}

int main()
{
double dResult = 0.0;

if ( read_double ( &dResult)) {
printf ( "You entered %f\n", dResult);
}

return 0;
}

关于c - 如何防止用户在c中输入0或负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47053160/

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