Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

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


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
Posted
Updated 6-Feb-18 21:07pm
v2

1 solution

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.
 
Share this answer
 
Comments
CPallini 7-Feb-18 3:16am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900