2

我想编写一个程序,它可以:当我输入“ Alan Turing ”时,它会输出“ Turing, A ”。但是对于我下面的程序,它输出“ uring, A ”,我想了很久但没弄清楚T去了哪里。这是代码:

#include <stdio.h>
int main(void)
{
char initial, ch;

//This program allows extra spaces before the first name and between first name and second name, and after the second name.

printf("enter name: ");

while((initial = getchar()) == ' ')
    ;

while((ch = getchar()) != ' ')  //skip first name
    ;

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
while((ch = getchar()) != ' ' && ch != '\n')
{
    printf("%c", ch);
}
printf(", %c.\n", initial);

return 0;
}
4

3 回答 3

3

你的错误在这里:

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
while((ch = getchar()) != ' ' && ch != '\n')
{
    printf("%c", ch);
}

第一个循环读取字符,直到找到非空格。那是你的'T'。然后第二个循环用下一个字符'u'覆盖它,并打印它。如果将第二个循环切换到do {} while();它应该可以工作。

于 2011-06-05T09:02:55.497 回答
2
while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}

这部分是错误的。那里的if永远不会匹配,因为该块仅在ch == ' '.

while ((ch = getchar()) == ' ');
printf("%c", ch);  //print the first letter of the last name

应该修复它。

请注意,getchar返回的是int,而不是 char。如果您想在某个时候检查文件的结尾,如果您将getchar' 的返回值保存在char.

于 2011-06-05T09:02:42.400 回答
0

使用 getchar() 从标准输入读取字符串并不是很有效。您应该使用 read() 或 scanf() 将输入读入缓冲区,然后处理您的字符串。这会容易得多。

无论如何,我在你的错误所在的地方添加了一条评论。

while((ch = getchar()) != ' ')  //skip first name
    ;

// Your bug is here : you don't use the character which got you out of your first loop.

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
于 2011-06-05T09:05:46.680 回答