2015-09-08 45 views
-1
#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 



int main() 
{ 

int upper=0; 
int digit=0; 
int i=0; 


char s[30]; 
char c; 

printf("Enter sentence: "); 
fgets(s, 30, stdin); 

//s[strlen(s) - 1] = '\0'; 


while(c=getchar() && c!='\n') 
{ 

    c = s[i]; 

    if(isupper(c)) 
    { 
     upper++; 
    } 

    if(isdigit(c)) 
    { 
     digit++; 
    } 


    i++; 
} 

printf("Number of upper case letters............... %d", upper); 
printf("\n"); 
printf("Number of digits........................... %d", digit); 
printf("\n"); 


printf("Program done. "); 





return 0; 
system("PAUSE"); 
} 

我如何刪除與fgets後多個換行符()?我試過在fgets()之後執行下面一行:如何在fgets()後刪除多個尾隨換行符?

s [strlen(s) - 1] ='\ 0';

但是,這並不工作,我的程序不會通過所有的代碼運行。

沒有代碼-----> S [strlen的(S) - 1] = '\ 0';


這裏是輸出:

Enter sentence: Whats UP 1234 















Number of upper case letters............... 3 
Number of digits........................... 4 
Program done. 
Process returned 0 (0x0) execution time : 9.340 s 
Press any key to continue. 

正如你可以看到我的程序能夠運行,但是我必須按多次輸入,有很多新行 的然後程序運行最後一段代碼。

程序是假設計算輸入的字符串 中的大寫字母和數字編號。有人可以解釋爲什麼會發生這種情況嗎?

+0

刪除'getchar'東西。基本上這意味着你必須按**輸入多次**才能看到你的輸出。我不知道你認爲它會增加你的程序。 – usr2564301

+0

謝謝!解決了這個問題。 – JonSnow

+0

@JonSnow如果您解決了這個問題,請回答或刪除您的問題,以幫助未來的帖子讀者解決同樣的問題。 – moffeltje

回答

-1

感謝Jongware:

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 



int main() 
{ 

int upper=0; 
int digit=0; 
int i=0; 


char s[30]; 
char c; 

printf("Enter sentence: "); 
fgets(s, 30, stdin); 

//correction: getchar() has been removed from the while condition. 
while(c!='\n') 
{ 

c = s[i]; 

    if(isupper(c)) 
{ 
    upper++; 
} 

if(isdigit(c)) 
{ 
    digit++; 
} 


i++; 
} 

printf("Number of upper case letters............... %d", upper); 
printf("\n"); 
printf("Number of digits........................... %d", digit); 
printf("\n"); 




return 0; 
system("PAUSE"); 
} 
+0

1)'char c; ... while(c!='\ n')'錯誤地嘗試測試'c'而不分配'c'值。 2)次要:如果'c'包含一個負值,'isupper(c)/ isdigit(c)'沒有很好的定義。最好使用'isupper((無符號字符)C)'3)如果's'不含''\ n''由於'30'或'EOF','while'環路接外'S [30]'。 – chux