2017-08-25 61 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置于原始模式,否则用户将不得不按回车。