2011-06-05 36 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