C-字符输入输出操作
时间:2020-02-23 14:31:52 来源:igfitidea点击:
在本教程中,我们将学习使用C编程语言处理字符输入输出操作。
到目前为止,我们已经了解了C编程语言中的数据类型,标记和变量。
现在让我们谈谈如何在程序中获取用户输入,然后返回一些输出。
字符输入
为了读取单个字符作为输入,我们使用getchar()函数。
在下面的示例中,我们将一个字符作为用户的输入,并打印该字符的ASCII码。
#include <stdio.h>
int main(void)
{
char ch;
printf("Enter any character: ");
ch = getchar();
printf("Entered character: %c\n", ch);
printf("ASCII value: %d\n", ch);
return 0;
}
Enter any character: A Entered character: A ASCII value: 65
字符输出
要输出单个字符,我们使用putchar()函数。
在下面的示例中,我们将单个字符作为输入,然后使用putchar()函数将其输出。
#include <stdio.h>
int main(void)
{
char ch;
printf("Enter any character: ");
ch = getchar();
printf("Entered character: ");
putchar(ch);
return 0;
}
Enter any character: A Entered character: A
测试字符
我们可以使用C库中的ctype.h头文件对字符进行测试。
以下是ctype.h文件中的一些函数,可用于测试字符。
如果传递的参数c满足条件,则所有给定的函数都将返回非零(true)值。
如果条件失败,那么我们将得到零(假)。
| 函数 | 说明 |
|---|---|
| isalnum(c) | c是字母数字字符吗? |
| isalpha(c) | c是字母字符吗? |
| isdigit(c) | c是数字吗? |
| islower(c) | 是小写字母吗? |
| isprint(c) | c是可打印的字符吗? |
| ispunct(c) | c是标点符号吗? |
| isspace(c) | c是空格字符吗? |
| isupper(c) | 是大写字母吗? |
用C编写程序以获取用户的字符输入,然后检查它是否为数字
我们将首先使用getchar()函数将字符作为输入,然后将使用isdigit()函数检查输入的字符是否为数字。
如果函数返回非零值,则该字符为数字,否则为非数字。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf("Enter character: ");
ch = getchar();
if (isdigit(ch)) {
printf("Entered character is a digit.");
}
else {
printf("Entered character is not digit.");
}
return 0;
}
Enter character: 6 Entered character is a digit.
在上面的代码中,我们使用if-else条件语句。
因此,如果isdigit(ch)返回非零值,则将执行if-blockprintf(" Entered character is a digit。");中的代码。
否则,将执行else块printf(" Entered character not digit");。

