如何使用getchar计算重复的字符数 [英] How to count repetitions of characters using getchar

查看:119
本文介绍了如何使用getchar计算重复的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用getchar()编写ac程序,它输出一个单词中的字符重复。

例如,如果输入是xxxyyyzzz,则输出应为333(因为每个都重复3次)如果输入是xxyzz,它应该是212.



我是初学者,对我来说似乎太棘手了。



我尝试了什么:



I am trying to write a c program using getchar() which outputs the repetition of characters in a word.
For example if the input is xxxyyyzzz the output should be 333 (as each are repeated 3 times) and if input is xxyzz it should be 212.

I am a beginner and it just seems too tricky for me.

What I have tried:

int nc ;
int count = 0;
for (nc=0 ; getchar()!=EOF;++nc) 
{
  printf ("%d",nc); 
}





我尝试使用这个程序,但无论它输出的是什么,只输出总字符,甚至包括换行符或输入。任何建议,将不胜感激 !感谢yoi



I tried working around with this program but no matter what it simply outputs the total characters, even including the newline or enter. Any suggestions would be appreciated ! Thank yoi

推荐答案

这是你的作业,所以我不给你任何代码!

但是......它并不复杂:

1)添加一个名为lastTime的char可变项并将其设置为getchar()返回的值。

2)添加一个名为count的整数,并将其设置为1 。

3)开始一个循环(做......虽然可能是一个不错的选择)

3.1)将一个字符读入一个变量。

3.2)将新字符与lastTime值进行比较。

3.2.1)如果它们相同,则递增计数

3.2.2)如果它们不同,则:

3.2.2.1)打印计数,并设置为1

3.2.2.2)将lastTime设置为新字符

3.3)如果你在输入的末尾,退出循环。

4)循环后,打印计数。
This is your homework, so I'll give you no code!
But ... it isn't complex:
1) Add a char variaable called lastTime and set it to the value returned by getchar().
2) Add an integer called count, and set it to one.
3) Start a loop (do...while is probably a good choice)
3.1) Read a character into a variable.
3.2) Compare the new character with the lastTime value.
3.2.1) If they are the same, increment count
3.2.2) If they are different then:
3.2.2.1) Print count, and set it to one
3.2.2.2) Set lastTime to the new character
3.3) If you are at the end of the input, exit the loop.
4) After the loop, print the count.


这篇关于如何使用getchar计算重复的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆