【问题标题】:Implementing counter when typing variable in array is typed键入数组中的变量时实现计数器
【发布时间】:2012-05-31 15:46:38
【问题描述】:

我修改了我的代码以包含一个计数器,它似乎正在工作,但我不喜欢它的实现方式。它似乎计算每个字母并在单词完成之前输出计数。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char** argv)
{
char C;
char vowels[]={'a','e','i','o','u'};
int counter=0;
    do
    {
    C = getchar();
    if(memchr(vowels,C, sizeof(vowels)))
        {printf("*\n");
        counter++;
        printf("%i", counter);
        }
    else
        {
        printf("%c",C);
        }



    }while (C!='Q');
}

我希望游戏输入的输出类似于

g*m*
2

我现在得到的只是

g*
1m*
2

我如何修改代码以便将大写字母也读为小写? C中是否有类似isupper或islower的东西?

【问题讨论】:

  • ctype.h中有函数toupper()tolower()。您可以使用它们来规范化字符。

标签: c arrays counter


【解决方案1】:

如果您希望计数器只打印一次,请将其移到 do-while 循环之外。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char** argv)
{
    char C;
    char vowels[]={'a','e','i','o','u'};
    int counter=0;
    while(1) {
        C = getchar();
        if(C == 'Q') { break; }
        C = tolower(C);
        if(memchr(vowels,C, sizeof(vowels))) {
            printf("*");
            counter++;
        }
        else
        {
            if(C == '\n') {
               printf("\n%i\n", counter);
               // reset the vowel counter here (dunno what the actual task is)
               counter = 0;
            } else {
               printf("%c",C);
            }
        }
    }

    return 0;
}

【讨论】:

  • 修复了一点,现在应该可以工作了。这里和那里有几个错别字
  • Viktor,代码如何在编辑的单词后打印计数器?
  • 是的,'true' 是另一个错误 - 我已经修复它并添加了计数器。
  • previous question来看,这很可能是一个未标记的作业;让 OP 找出问题所在比给他一段完成的代码更有启发意义。
  • 好的,不多说了。沉默是金。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多