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. What is wrong with the code?
Output: Key in value: 0 01111110 10100000000000000000000 00111111010100000000000000000000
CodePudding user response:
initialize i: putting the equivalent of C's
int i = 0;
in your prog lang before entering the while loop should do the job.
CodePudding user response:
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; so, you should test if (str[i] == '0' || str[i] == '1')
.
And, before that, you should initialize i: int i = 0
.
CodePudding user response:
You could use strtok to extract your characters. 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:-
#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;
}
}
}