2011-06-05 35 views
2

的getchar我想写一个程序,它可以: 当我进入,说:“阿兰·图灵”时,输出“图灵,A”。 但对于我的后续程序,它输出“uring,A”,我想了很久,但未能弄清楚T去哪里。 下面是代码:问题在C

#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; 
} 

回答

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();它应该工作。

+0

伟大的解决方案!谢谢! – asunnysunday 2011-06-05 09:39:13

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的返回值,这将会以字节为单位。

+0

+1“如果你想检查文件的结尾”。如果你想?我会把它归类为必不可少的。 'ch'应该声明为'int',每个循环都需要检查'EOF'。就目前而言,代码有很多机会消失在无限循环中。 – 2011-06-05 09:07:58

0

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

无论如何,我在bug的地方添加了一条评论。

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 
}
+2

“使用getchar()从标准输入中读取字符串并不是真的有效。”真? – 2011-06-05 09:11:42

+2

+1 @Charles,并且'read'不在标准C库(它是POSIX)中,'scanf()'很难正确使用。 – pmg 2011-06-05 09:32:14