[英]Reading multiple input types from console in C
我想在 C 中有一个整数或一个字符串。
我想过scanf(("%d, &first) || ("%s", second));
用int first
和char second[20]
,但我不确定这是否是可行的方法 - 你有吗建议?
提前致谢!
一个简单的解决方案是
#include <stdio.h>
#include <stdlib.h>
int main()
{
long num = 0;
char str[40];
char *end = NULL; // pointer to end char
printf("Enter string or number : ");
fgets(str, sizeof(str), stdin); // works for string with space too
num = strtol(str, &end, 10);
if(*end != '\n') // last character is newline which not removed by fgets
{
printf("You Entered String is %s", str);
}
else if(end > str)
{
printf("you Entered Number is %ld", num);
}
else
{
printf("Nothing");
}
return 0;
}
您可以根据需要使用scanf()
并检查其返回值:
#include <stdio.h>
int main() {
int first;
char second[20];
if (scanf("%d", &first) == 1) {
printf("you typed an integer value: %d\n", first);
} else
if (scanf("%19s", second) == 1) {
printf("you typed a word: %s\n", second);
} else {
printf("input error\n");
}
return 0;
}
但是请注意, 92.34.12.34
将由scanf()
处理为整数92
后跟其他字符.34.12.34
,留在stdin
用于下一个输入操作,这可能不是您的意图。 使用fgets()
一次读取一整行允许更准确的输入验证。
将输入的文本作为字符串,然后识别它是 Int 还是 String
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // atoi
#include <ctype.h> // isdigit
int IsNumber(const char* text){
for(int i=0; i < strlen(text); i++){
// isdigit returns a non-zero value if it’s a digit else it returns 0
if(isdigit(text[i]) == 0)
return 0;
}
return 1;
}
int main(){
char Buffer[256];
scanf("%s", Buffer);
if(IsNumber(Buffer)){
int Number = atoi(Buffer);
printf("entered text is Integer: %d\n", Number);
} else {
printf("entered text is String: %s\n", Buffer);
}
return 0;
}
如果您只想检查数字或字符串,请将匹配字符串更改为0123456789
( strspn()
第二个参数)。 如果要检查其他字符,只需将这些字符添加到strspn()
的第二个参数即可。
例如,如果您要检查 IP 地址,它由.
, 将.(dot)
添加到字符串( strspn()
第二个参数)
#include <stdio.h>
#include <string.h>
void isNumberOrString(char* str)
{
int len = strlen(str);
if(len == 0)
{
printf("Empty\n");
return;
}
int len2 = strspn(str, ".0123456789"); // scans str and return the number of characters that match characters in the string (.0123456789)
if(len == len2)
{
if(strchr(str, '.') == NULL)
{
printf("Numbers\n");
}
else
{
printf("Numbers with dots \n");
}
}
else
printf("A string\n");
}
int main()
{
char str[] = "192.168.43.8" ;
char str2[] = "123454612343" ;
char str3[] = "Hello World";
isNumberOrString(str);
isNumberOrString(str2);
isNumberOrString(str3);
return 0;
}
我们可以使用strspn()函数。 它将返回与输入字符串匹配的字符数。 如果字符串的总长度等于strpsn
返回的长度,则它是一个数字。 我补充说. (dot)
. (dot)
也包括 IP 地址。
输出用于三个测试用例:
Numbers with dots
Numbers
A string
有关strspn()
更多信息,请参阅链接: https : strspn()
:~: strspn()
= The% strspn()
20string%20to%20be%20scanned 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.