[英]How can i make a string that only accepts numbers and the character “.” in c?
我試圖在 c 中編寫一個程序來檢測數字是整數還是浮點數,如果是浮點數,則計算小數位數。
但是我在這里遇到了一個問題,當我插入一個浮點數時,因為“。” 該程序說它是一個“單詞”而不是一個數字,因為我讓它只接受數字並且我陷入了 while 循環。
我的代碼:
#include<stdio.h>
#include <string.h>
#define BASE 10
main()
{
int length, number;
char str[10];
char ch = '.';
char *ret;
char *endptr;
do{
printf("Enter string: ");
scanf("%s", str);
number = strtol(str, &endptr, BASE);
}while (*endptr != '\0' || endptr == str);
ret = strchr(str, ch);
if(ret > 0){
length = strlen(ret);
printf("decimal places: %d\n", length - 1);
}
else {
printf("the number is integrer\n");
}
return 0;
}
僅當您知道輸入是 integer 時,使用strtol
才有意義。 如果您知道輸入是浮點數,則可以使用strtod
代替。 沒有可以處理這兩種類型的 function ,除非您想將整數作為浮點數處理。
為了確定輸入是 integer、浮點還是無效輸入,最好自己檢查輸入字符串,例如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main( void )
{
char str[100];
retry_input:
//prompt user for input
printf( "Enter number: " );
//read one line of input
if ( fgets( str, sizeof str, stdin ) == NULL )
{
fprintf( stderr, "input error!\n" );
exit( EXIT_FAILURE );
}
//if newline character exists, remove it
str[strcspn(str,"\n")] = '\0';
//this variable keeps track of the number of digits encountered
int num_digits = 0;
//this variable specifies whether we have encountered a decimal point yet
bool found_decimal_point = false;
//inspect the string one character at a time
for ( char *p = str; *p!='\0'; p++ )
{
if ( *p == '.' )
{
if ( found_decimal_point )
{
printf( "encountered multiple decimal points!\n" );
goto retry_input;
}
found_decimal_point = true;
}
else if ( isdigit( (unsigned char)*p ) )
{
num_digits++;
}
else if ( *p != '+' && *p != '-' )
{
printf( "encountered unexpected character in input!\n" );
goto retry_input;
}
else if ( p - str != 0 )
{
printf(
"sign characters (+/-) are only permitted at the start "
"of the string!\n"
);
goto retry_input;
}
}
if ( found_decimal_point )
{
//input is floating-point
printf( "The input is float and has %d digits.\n", num_digits );
}
else
{
//input is integer
printf( "The input is integer and has %d digits.\n", num_digits );
}
return EXIT_SUCCESS;
}
請注意,該程序還將計算遇到的位數,並在程序結束時打印總數。 由於您在問題中聲明要計算“小數位數”,這可能就是您想要的。
另請注意,該程序不接受指數表示法的浮點數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.