How do I replace two a's in a string with an '*'

Apr 14, 2018
2
0
10
Hey guys so for my assignment I have to replace two a's with an '*' from a string of unknown input length in C. The challenge is I am only allowed to use the getchar() and the putchar() function.
With an array it would have been easier but I am not even allowed to use that. I am just allowed to use loops and ifs.


This is what I have tried. But it replaces all the a's with '*'.


This is what I have so far.

Code:
#include <stdio.h>

int ch;

int main()
{
    
    while ((ch = getchar()) !=EOF && ch != '\n'  ) { 
    
    
    if(ch=='a'){
		if(ch=='a')
		{
		ch='*';
	}
}

putchar(ch);
}

putchar('\n');
return 0;
}

Is this even the right approach?
It just replaces all the a's with a '*'. But it should only replace two a's with a '*'.
Could someone help me or at least lead me to the right solution?
Thank you in advanc.
 
Not working in C, but...
Initialise the integer i=0 and try including in the loop the condition i<2 for ending it (so either reaching the end of the string, or i<2) and apart from replacing a with * increment also i:
if(ch='a') { ch='*' and i++.
 
Apr 14, 2018
2
0
10


Hi thank you for your answer
but I am not quite sure what you mean by i<2
I tried it but I am not getting to the solution
 

gigantusmagnus

Prominent
Dec 22, 2017
19
0
590
the first 2 a's? you can add a counter value at for function, and add if the counter is 2 or more, the function stops

I don't remember much about C's codes

but its like this iirc

int a = strlen(string);

for(int i = 0; i<a; i++){
int cnt = 0;

if (cnt != 2){

*your codes here

}
printf(*the final strings);
}
 


#include <stdio.h>
int ch;
int main()
int i=0
{
while ((ch = getchar()) !=EOF && ch != '\n' || i==2)
{
if(ch=='a')
{
if(ch=='a')
{
ch='*';
i++;
}
}
putchar(ch);
}
putchar('\n');
return 0;
}

Something like that. Not sure about the syntax...