[英]Distinguish a letter input from an integer input in c
There are two kinds of input that can be provided: 可以提供两种输入:
50
b 2 40
I have to distinguish both the cases and then take further actions accordingly. 我必须区分这两种情况,然后采取相应的措施。 Here's what I have tried:
这是我尝试过的:
char input[100];
fgets(input, 100, stdin);
printf("%s", input);
int count = 0;
char a[3][100];
int j=0, i=0;
while(true){
a[count][j] = input[i];
j++; i++;
if(input[i] == '\n'){
break;
}
if(input[i] == ' '){
count++;
j = 0;
i++;
}
}
printf("%d\n", count);
printf("%s\n", a[0]);
printf("%s\n", a[1]);
printf("%s\n", a[2]);
For example, input: 例如,输入:
b 6767 9090
output: 输出:
b 6767 9090
b 6767 9090
2
b����
67670
9090
Can somebody help me on how to do this? 有人可以帮我吗? I was suggested previously to use fgets.
以前建议我使用fgets。 As I am a beginner in C, I am having difficulty figuring out how to achieve this.
因为我是C语言的初学者,所以我很难确定如何实现此目标。
遇到空格时,您应该设置'\\0'
或null终止符,或者您可以预先将数组的所有元素设置为0或null,如下所示-
char a[3][100] = {0};
另外,如果用户输入的字符串超过三个单词(即count> 2),则该程序将崩溃,因为loop while(true)会一直尝试直到命中\\ n字符。
I found out that the best way to do this would be: 我发现最好的方法是:
char inp[25];
scanf("%s", inp);
if(inp[0] == 'b'){
int r, v;
scanf("%d %d", &r, &v);
}
else{
int v = atoi(inp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.