[英]How to check if the entered character is a digit?
Given task is:给定的任务是:
Enter 10 characters.输入 10 个字符。 For each character entered the corresponding function prints whether it is a digit 0-9 or not.(Also I use older compiler if anyone concerns about my "gets()" and goal is to do this without pointers.)对于输入的每个字符,相应的函数会打印它是否是数字 0-9。(如果有人担心我的“gets()”,我也使用旧编译器,目标是在没有指针的情况下执行此操作。)
So far I tried something like this, but for some reason it does not work:到目前为止,我尝试过这样的事情,但由于某种原因它不起作用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char character[10][1];
char zero ='0';
char nine ='9';
int i;
printf("Enter 10 characters:\n");
for(i=0;i<10;i++){
gets(character[i]);
}
for(i=0;i<10;i++){
if(strcmp(character[i],zero)>=0 && strcmp(character[i],nine)<=0){
printf("%d. character '%c' is a digit.", i, character[i]);
}
else{
printf("%d. character '%c' is not a digit.", i, character[i]);
}
putchar('\n');
}
return 0;
}
Also I tried this, but it can not output correctly characters:我也试过这个,但它不能正确输出字符:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char character[10][1], pom[10][1];
int num_character[10];
int i;
printf("Enter 10 characters:\n");
for(i=0;i<10;i++){
gets(character[i]);
strcpy(pom[i],character[i]);
num_character[i]=atoi(character[i]);
}
for(i=0;i<10;i++){
if(num_character[i]!=0){
printf("Character '%c' is digit.", pom[i]);
}
else{
printf("Character '%c' is not digit.", pom[i]);
}
putchar('\n');
}
return 0;
}
isdigit()
also does not work after I include ctype
header. isdigit()
在我包含ctype
标头后也不起作用。
You are doing several things wrong here, gets is never recommended and fgets will put new line character in the end.您在这里做错了几件事,从不建议使用 gets 并且 fgets 将在最后放置换行符。
The syntax for strcmp is: strcmp 的语法是:
int strcmp(const char *s1, const char *s2);
You need two strings as input in strcmp but you are using a string and a character.您需要两个字符串作为 strcmp 中的输入,但您使用的是一个字符串和一个字符。
Here, it is better to use a character array than a 2D array.在这里,最好使用字符数组而不是二维数组。
#include <stdio.h>
int main(void)
{
char character[10]; //a simple character array
char zero ='0';
char nine ='9';
int i;
printf("Enter 10 characters:\n");
for(i=0;i<10;i++){
scanf(" %c", &character[i]); //scan characters
}
for(i=0;i<10;i++)
{
if(character[i] >= zero && character[i] <= nine) //print
printf("%d. %c is a digit \n", i+1, character[i]);
else
printf("%d. %c is not a digit \n", i+1, character[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.