简体   繁体   English

验证C数组中的输入并检查char的值

[英]Validate Input in C array and check value of char

I'm trying to get user input of a string in format XXXXXXXXB where X is a digit and B is a char. 我正在尝试让用户输入格式为XXXXXXXXB的字符串,其中X是数字,B是字符。 I then want to validate the input is the correct format and check the Char to see if is A,B,C,D so i can out put the correct thing 然后,我想验证输入的格式正确,并检查字符以查看是否为A,B,C,D,以便我可以输入正确的内容

problem i am having is how do i check the value of the char?? 我遇到的问题是如何检查char的值? this is my code 这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

void validate(char array[]){
int i=0;
for(i=0;i<9;i++){
    if(isdigit(array[i])){
    printf("Valid int %d at %d\n",array[i],i);
    }

    else if(isalpha(array[i])){
    printf("Valid alpha %c at %d\n",array[i],i);

        switch(isalpha(array[9])){
        case 'a':
            printf("Char a");
            break;
        case 'b':
            printf("Char b");
            break;
        case 'c':
            printf("Char c");
            break;
        case 'd':
            printf("Char d");
            break;
        }
    }

}
}

  int main(void) {
printf("Please Enter a string in format xxxxxxxxb x=digit b=char\n");
fflush(stdout);
char input[9];

gets(input);
validate(input);

return 0;
}

You might want to consider two things- 您可能要考虑两件事-

1) Check for proper index - array[9] is the value at 10th index of an array 1) 检查索引是否正确 array[9]是数组10th index处的值

2) Check for case sensitive - b is not same as B . 2) 检查是否区分大小写 bB So you might want to either compare using ascii values or covert the input char into lower case before comparing in switch 因此,您可能需要使用ascii值进行比较,或者将输入的char转换为小写,然后再在switch进行比较

You're not checking the right spot in the array. 您没有检查阵列中的正确位置。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

void validate(char array[]){
int i=0;
for(i=0;i<8;i++){
if(isdigit(array[i])){
printf("Valid int %d at %d\n",array[i],i);
}

else if(isalpha(array[8])){
printf("Valid alpha %c at %d\n",array[i],i);

    switch(isalpha(array[9])){
    case 'a':
        printf("Char a");
        break;
    case 'b':
        printf("Char b");
        break;
    case 'c':
        printf("Char c");
        break;
    case 'd':
        printf("Char d");
        break;
    }
}

}
}

int main(void) {
printf("Please Enter a string in format xxxxxxxxb x=digit b=char\n");
fflush(stdout);
char input[9];

gets(input);
validate(input);

return 0; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM