如何解决使C在单个输入中读取多个字符
我是C语言的新手,我想编写一个程序来接收一个单词,说“ Aloha”作为输入,记下单词中的所有元音和辅音,并计算单词中的字符数
我已经创建了确定单个字符是夏威夷语中的元音还是辅音的函数,但是我不知道如何使程序读取多个字符作为输入。例如,在下面的代码中
#include <stdio.h>
int is_vowel(char);
int is_consonant(char letter);
int main() {
char letter;
int vowel,consonant;
printf("Please input a Hawaiian word:");
scanf("%c",&letter);
vowel = is_vowel(letter);
consonant = is_consonant(letter);
if (vowel == 1) {
printf("%c is a vowel. \n",letter);
} else {
printf("%c is not a vowel. \n",letter);
}
if (consonant == 1) {
printf("%c is a consonant. \n",letter);
} else {
printf("%c is not a consonant. \n",letter);
}
}
当用户输入“ Aloha”时,输出为 “ A是元音。 A不是辅音”,然后停止。
代替“ A是元音,A不是辅音。l不是元音,l是辅音”等。
如何让C一次读取输入中的所有字符,并获得该函数(示例代码中未包含)来检查每个字符?
谢谢!
解决方法
输入应为:a-z或A-Z
#include <stdio.h>
#include <string.h>
int is_vowel(char ch) {
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u') return 1;
else if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') return 1;
else return 0;
};
int is_consonant(char ch) {
if(is_vowel(ch) == 0) return 1;
else return 0;
};
int main()
{
char letter[100];
int vowel,consonant;
int i,length;
printf("Please input a Hawaiian word: ");
scanf("%[^\n]s",&letter);
length = strlen(letter);
for(i=0; i<length; i++) {
vowel = is_vowel(letter[i]);
consonant = is_consonant(letter[i]);
if (vowel == 1) {
printf("%c is a vowel. \n",letter[i]);
}
else {
printf("%c is not a vowel. \n",letter[i]);
}
if (consonant == 1) {
printf("%c is a consonant. \n",letter[i]);
}
else {
printf("%c is not a consonant. \n",letter[i]);
}
printf("\n");
}
return 0;
}
,
有用的工具是:
- 数组:可以使用索引访问的连续变量序列
-
%s
格式指定符:让scanf()
读取字符串(NUL终止的字符序列) -
for(initializer; condition; update) { body }
循环:- 执行
initializer
- 在
body
为真时重复执行update
和condition
- 执行
尝试一下:
#include <stdio.h>
int is_vowel(char);
int is_consonant(char letter);
int main() {
char letters[102401]; /* allocate enough size */
int i;
printf("Please input a Hawaiian word:");
if (scanf("%102400s",letters) != 1) { /* read input with length limit and check if it succeeded */
puts("input error");
return 1;
}
for (i = 0; letters[i] != '\0'; i++) { /* loop over the letters read */
char letter = letters[i];
int vowel,consonant;
vowel = is_vowel(letter);
consonant = is_consonant(letter);
if (vowel == 1) {
printf("%c is a vowel. \n",letter);
} else {
printf("%c is not a vowel. \n",letter);
}
if (consonant == 1) {
printf("%c is a consonant. \n",letter);
} else {
printf("%c is not a consonant. \n",letter);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。