[英]C char input instead of int and 2 digit char conversion to int
這段代碼只是一個例子。 在此代碼中,如果用戶輸入 1 位數字,它可以正常工作,但如果用戶輸入超過 1 位數字,則number=number-'0';
代碼變得無用。 但是如果用戶類型不是 int 事物程序返回 2 次我不知道為什么,我的程序也應該為 2 位代碼啟用(可用)。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number;
donus:
number=getchar();
if (isdigit(number)==0)
{
printf("invalid code");
goto donus;
}
else
{
number=number-'0';
switch (number)
{
case 1:
printf("%d",number);
}
}
return 0;
}
正如@Weather Vane的評論中所述,您需要將number
本身乘以 10 並在從digit
減去第 48 個 ASCII 字符零后添加。
您可以動態處理此方法(請注意注釋以進行解釋):
#include <ctype.h> // isdigit()
#include <stdio.h> // puts(), scanf(), printf()
#include <stdlib.h> // malloc()
#include <string.h> // strlen()
#define MAX 5
int to_int(const char *str) {
int mult = 1; // multiplier initialized to 1 to not get 0
int rec = 0;
unsigned int len = strlen(str);
for (int i = len - 1; i >= 0; i--) { // till len - 1 (avoiding NUL term.)
rec += ((int)str[i] - '0') * mult; // dynamic approach
mult *= 10;
}
return rec;
}
int main(void) {
// allocating required bytes in memory
char *input = (char *)malloc(sizeof(char) * MAX);
puts("Enter a number (to be read as char*): ");
scanf("%5s", input);
// Verification of user input
for (unsigned int i = 0, len = strlen(input); i < len; i++)
if (!(*(input + i) > '0' && *(input + i) < '9')) {
puts("The input must be a number");
return 1;
}
// Calling the dynamic conversion algorithm
int number = to_int(input);
printf("The final result (int): %d\n", number);
return 0;
}
示例測試用例:
Enter a number (to be read as char*):
12345
The final result (int): 12345
Enter a number (to be read as char*):
99999
The final result (int): 99999
Enter a number (to be read as char*):
-1
The input must be a number.
Enter a number (to be read as char*):
55a
The input must be a number.
這里MAX
常數的值是可調的,但不要忘記在scanf()
中將%Ns
更改為與MAX
相同,因為在輸入 N 長度后,rest 會被截斷以避免 integer 溢出,即保持MAX
和%Ns
scanf()
9 中的%Ns
對於 32 位機器被認為是安全的,因為在大多數 32 位系統中INT_MAX
是 2147483647。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.