我是C编程新手:D。
这是C编程-一种现代方法中的7.1编程项目。例如,输入的名字和姓氏是Lloyd Fosdick,预期的结果应该是L. Fosdick。我尝试计算名字中的字符数(本例中为5)。然后,当i>名字的长度时,使用putchar()开始打印,如下面的代码所示。
#include <stdio.h>
int main(void)
{
char ch, first_ini;
int len1 = 0, i = 0;
printf("Enter a first and last name: ");
ch = getchar();
first_ini = ch;
printf("The name is: ");
while (ch != ' '){
len1++;
ch = getchar();
}
while (ch != '\n')
{
i++;
if (i <= len1) {
ch = getchar();
}
else {
putchar(ch);
ch = getchar();
}
}
printf(", %c", first_ini);
return 0;
}
我得到的结果是L,而不是Fosdick,L
答案 0 :(得分:2)
您应该尝试对代码进行以下更改。
#include <stdio.h>
int main(void)
{
char ch, first_ini;
int len1 = 0, i = 0;
printf("Enter a first and last name: ");
ch = getchar();
first_ini = ch;
printf("The name is: ");
while (ch != ' '){
len1++;
ch = getchar();
}
while (ch != '\n')
{
ch = getchar();// get the characters of second word
if(ch != '\n')
putchar(ch);// print the characters of second word but avoid newline
}
printf(", %c", first_ini);
return 0;
}
您的代码的问题在于,仅当第二个单词的长度大于第一个单词的长度时,它才开始打印第二个单词的字符。