gpt4 book ai didi

c - 通过读取字符串检测数据类型

转载 作者:太空狗 更新时间:2023-10-29 15:35:06 26 4
gpt4 key购买 nike

所以我想知道,检查用户输入 (stdin) 的最简单方法是什么。我得出结论,理想情况下是扫描用户输入并打印出结果。

虽然现在我有点困惑,我应该怎么做。这是我的想法:

#include <stdio.h>
int main(){

char input[30];

printf("Please enter text\n");
scanf("%s", &input);

...

所以这是我无法真正理解的部分。所以我想做的是逐个字符地遍历整个单词(输入)。

基本上,如果字符串仅包含数字 (0-9),我希望输入被识别为数字。否则,将其检测为字符串。

我已经做了很多研究(尽管请记住我是一个绝对的初学者),有一种方法可以使用 strcmp() 函数,但我宁愿完全避免使用其他库,例如 string.h就像我试图解释的那样,用简单的方法来做。

最佳答案

就去做吧。

#include <stdio.h>

int checkIfNumber(const char *word) {
/* check until the string ends */
while (*word != '\0') {
/* return 0 if the character isn't a number */
if (*word < '0' || '9' < *word) return 0;
/* proceed to the next character */
word++;
}
/* no characters other than numbers found */
return 1;
}

int main(void){

char input[30];

printf("Please enter text\n");
scanf("%29s", input);

if(checkIfNumber(input)) {
printf("%s is number\n", input);
} else {
printf("%s is string\n", input);
}

return 0;
}

请注意,数字的字符代码在 C 中是连续的,因此这种基于范围的方法对于检查字符是否为数字(十进制数字)很有用。此方法可能不适用于字母表,尤其是在使用非 ASCII 字符代码的系统上。

N1256 5.2.1 字符集

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

关于c - 通过读取字符串检测数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463185/

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