读取用户输入,直到遇到特定字符

时间:2017-08-25 15:36:27

标签: c

有人可以提供一些例子吗?谢谢:))

#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循环?

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

测试结果:

你好5432用户#

位数:4个字母:9个

4 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

尝试类似:

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

}
while(c != '!');

答案 2 :(得分:0)

是的,你需要使用一个循环,或者一段时间:

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

或while代码:

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

答案 3 :(得分:0)

POSIX getdelim函数完全符合您的要求(大多数代码都使用getline,但它与额外参数完全相同)。请注意分隔符在缓冲区大小内的可能性。

此外,对于交互式输入,您可能希望将TTY置于原始模式,或者用户必须仍然按Enter键。

相关问题