此代码适用于少于五个字母的单词:(但不适用于更高的单词)
#include <stdio.h>
int main(void)
{
const int size = 5;
char str1[size], str2[size], str3[size];
printf("Type word1: ");
scanf("%s", str1);
printf("Type word2: ");
scanf(" %s", str2);
printf("Type word3: ");
scanf(" %s", str3);
printf("First chars: '%c', '%c' e '%c'.\n", str1[0], str2[0], str3[0]);
return 0;
}
正确运行的唯一方法是增加“大小”变量?我想知道是否可以在不必增加“大小”变量的情况下正确处理更大的单词。
最佳答案
这会让你接近
只需保存第一个 char
#include <stdio.h>
int main(void)
{
char str[3];
printf("Type word1: ");
scanf(" %c%*s", &str[0]);
printf("Type word2: ");
scanf(" %c%*s", &str[1]);
printf("Type word3: ");
scanf(" %c%*s", &str[2]);
printf("First chars: '%c', '%c' e '%c'.\n", str[0], str[1], str[2]);
return 0;
}
关于c - 如何获取 C 中多个条目的第一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27789120/