[英]How to check a string contain a certain value in C
void main
{
printf("\n Key in value: ");
fgetchar();
fgets(str , CHAR_SIZE, stdin);
//Remove white space
remove_white_spaces(str);
printf("%s",str);
while (str[i])
{
if(str[i] == '0' && str[i] == '1')
{
i++;
continue;
}
else
{
printf("Wrong number input")
break;
}
I want to check whether the user has type in the correct input.我想检查用户是否输入了正确的输入。 For example, I have key in 0 01111110 10100000000000000000000. After removing the white space, the str input became 00111111010100000000000000000000. From this str, I want to check that the user has only key in 0 and 1. However, the str value does not go in the if condition but the else condition instead.例如,我有 key in 0 01111110 101000000000000000000000。去掉空格后,str输入变成了001111110101000000000000000000000。从这个str中,我想检查用户是否只有key in 0和1。但是,str值没有Z394D1F91FBA276BZ394D1F91FBA76B在 if 条件下,但在 else 条件下。 What is wrong with the code?代码有什么问题?
Output: Key in value: 0 01111110 10100000000000000000000 00111111010100000000000000000000 Output:键入值:0 01111110 10100000000000000000000 00111111010100000000000000000000
First of all, you are checking that str[i]
should be equal to 0 and equal to 1 – and that doesn't make any sense, because an element in the array can be only one value, 0 or 1;首先,您正在检查str[i]
是否应该等于 0和1——这没有任何意义,因为数组中的元素只能是一个值,0或1; so, you should test if (str[i] == '0' || str[i] == '1')
.所以,你应该测试if (str[i] == '0' || str[i] == '1')
。 And, before that, you should initialize i: int i = 0
.而且,在此之前,您应该初始化 i: int i = 0
。
initialize i: putting the equivalent of C's初始化 i:把 C 的等价物
int i = 0;
in your prog lang before entering the while loop should do the job.在进入 while 循环之前,在你的 prog lang 中应该可以完成这项工作。
You could use strtok to extract your characters.您可以使用 strtok 提取字符。 Also there's a flaw in your logic.你的逻辑也有缺陷。 it should be if (str[i] == '0' || str[i] == '1'
to check if the value is '0' OR '1'. Here's a sample implementation you could refer to:-应该是if (str[i] == '0' || str[i] == '1'
来检查值是否为 '0' 或 '1'。这是您可以参考的示例实现:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CHAR_SIZE 100
int main()
{
char str[CHAR_SIZE];
printf("\n Key in value: ");
getchar();
fgets(str, CHAR_SIZE, stdin);
char *tok;
tok = strtok(str, "\n");
int i = 0;
tok++; //skip the first character which is a space
while (*tok != 0x00)
{
if (*tok <= 0x31 && *tok >= 0x30)
tok++;
else
{
printf("Wrong number input ==> %c \n", *tok);
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.