gpt4 book ai didi

c - 如何在C中连接数组中的字符

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:49 25 4
gpt4 key购买 nike

我想从键盘获取一个值(1、2 或 3 位数字),并希望在控制台上打印出该值。

我有,

char val[i] // value from a Keypad from 1 through 120
// so, val[i] could be one, two or three digit number.

我想做的是,

if (val[i] == 1)
printf("The number you got is %d", val[i]); // prints "The number you got is 1"
else if ((val[i] == 2)
printf("The number you got is %d", val[i]); // prints "The number you got is 2"
.
.
else if ((val[i] == 10)
printf("The number you got is %d", val[i]); // prints"The number you got is 10"
.
.
else if ((val[i] == 120)
printf("The number you got is %d", val[i]); // prints"The number you got is 108"
else printf("Error!"); // prints "Error!"

请帮帮我。预先感谢您的帮助。

最佳答案

应该没问题


#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int isNumber(char* s)
{
for (int i = 0; i < strlen(s); i++)
if (isdigit(s[i]) == 0)
return 0;

return 1;
}

int main()
{
char * a = (char*) malloc(4);
scanf("%s",a);

int i = atoi(a);

if(isNumber(a) && i>= 1 && i <= 120)
{
printf("The number you got is %d\n", i);
} else printf("Error!");
}

在我的机器上:

Input : 120

Output : The number you got is 120

Input: 12A

Output : Error!

关于c - 如何在C中连接数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567611/

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