2017-08-25 87 views
-2

有人可以給我提供一些例子嗎?謝謝:)閱讀用戶輸入,直到遇到特定字符

#include <stdio.h> 

int main() 
{ 
    int tcount = 0, ccount = 0, dcount = 0; 
    char ch; 
    printf("Enter your characters (! to end): \n"); 

    /* What program code to write to get the result? */ 

    printf("digits: %d\n", dcount); 
    printf("letters: %d\n", ccount); 
    return 0; 
} 

是用循環嗎?

for (tcount=0;tcount<10;tcount++) 
    { 
     scanf("%c",&ch); 
     if(ch == '!') 
      break; 
    } 

測試結果:

你好5432用戶#

位數:4個字母:9

+0

提示:'getchar()' –

+0

您的任務是否將其限制爲最多10個字符的輸入?如果是這樣,for循環是適當的。如果不是,那麼一個while循環將是更合適的選擇。 –

+0

除非您可以將輸入置於原始模式,否則用戶將不得不在輸入結果前按下輸入鍵。 – Jasen

回答

4

我會建議你使用getchar()而不是用於讀取單個字符的scanf()

或者,如果你有,你要跳過空格領先

scanf(" %c",&ch); 
    ^    Note the space 

下面是一個簡單的例子,這可能對您有所幫助,使用功能isdigit()isalpha()ctype.h庫。

int c, numberCounter = 0, letterCounter = 0; 
while ((c = getchar()) != '!') 
{ 
    if (isalpha(c)) 
    { 
     letterCounter++; 
    } 
    else if (isdigit(c)) 
    { 
     numberCounter++; 
    } 
} 

如果您無法使用另外的庫,例如ctype.h,看看在ASCII表,例如

if (c >= '0' && c <= '9') // '0' == 48, '9' == 57 
{ 
    // c is digit 
} 
+0

它正在工作!謝謝:) – BEX

+0

沒有使用額外的庫有另一種方法嗎? – BEX

+2

@Bexie C庫在那裏可以使用!你可以用'if(ch> ='0'&& ch <='9')來測試一個數字,因爲C *要求*數字要連續編碼。但是,雖然ASCII字符集是常用的,但C不需要使用相同的字母表。因此,使用'isalpha()'不僅是可移植的,而且比'if'(ch> ='A'&& ch <='Z'|| ch> ='a'&& ch <='z')' 。 [EBCDIC集](https://en.wikipedia.org/wiki/EBCDIC)是不連續的。 –

0

試着這麼做:

do 
{ 
    char c = getchar(); 
    if(c!='!') 
    { 
     ... do something .... 
    } 

} 
while(c != '!'); 
0

是的,你需要使用一個循環,或同時:

for (tcount=0;tcount<10;tcount++) 
{ 
    scanf("%c",&ch); 
    if(ch == '!') 
     break; 
} 

或同時代碼:

while(ch != '!'){ 
    scanf("%c",&ch); 
    printf("There are nothing to see here"); 
} 
0

POSIX getdelim函數完全符合您的要求(大多數浮動代碼使用getline,但除額外參數外,它完全相同)。請注意,分隔符而不是發生在緩衝區大小內的可能性。

此外,對於交互式輸入,您可能希望將TTY置於原始模式,否則用戶將不得不按回車。