Click here to Skip to main content
15,905,068 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

What I have tried:

C++
#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;
}
Posted
Updated 13-Apr-18 15:23pm
v2

1 solution

This code is wrong and need rewrite
C++
if(ch=='a'){
    if(ch=='a'){
        ch='*';
    }
}
putchar(ch);

As per assignment, when you encounter an 'a', you know what to do only when you know the next letter.
You need a variable to tell you if you have an 'a' on hold or not.
And you need to adapt the code to handle if a 'a' is on hold or not.
The code will look like:
C++
if(ch=='a'){
  if (a 'a' is on hold) {
    putchar('*');
    reset number of 'a' in hold
  }
  else {
    add a 'a' in hold
  }
}
else {
  if (a 'a' is on hold) {
    ...
  }
  ...
}

[Update]
Quote:
could you please explain what you mean by "in hold" and "on hold" english is not my first language

Sample input
Input   on Hold   Output
  b                 b
  a       a
  n                 a n
  a       a
  a                 *
  a       a
  n                 a n
  a       a
  \n                a \n

You can translate 'on hold' as waiting for next input. Said otherwise: you don't know what to do with a 'a' until you know if there is a second 'a'.
 
Share this answer
 
v5
Comments
Member 13778651 14-Apr-18 3:25am    
sry but I am confused I have never heard of the terms 'in' or 'on' in C. I have problems understanding your solution-
Patrice T 14-Apr-18 3:35am    
Because it is only a description, not C language.
Member 13778651 14-Apr-18 3:47am    
so in hold would be for example , lets say we have a variable called check, so reset number of 'a' in hold would be : check = a?
Patrice T 14-Apr-18 4:27am    
"so reset number of 'a' in hold would be : check = a?"
check= 0 or check= false
Member 13778651 14-Apr-18 8:10am    
ok I think i almost understand one last question could you please explain what you mean by "in hold" and "on hold" english is not my first language

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