1

I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged.

#include <iostream>
#include <string>

using namespace std;

void removeAllOccurrence(char text[], char letter)
{
int off;
int i;
i = off = 0;
    if (text[i] == letter)
    {
        off++;
    }
    text[i] = text[i + off];
}

int main() {

string text;
char letter;
string newText;

cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;


cout << "your new text is: " << removeAllOccurrence << endl;
system("pause");
return 0;
}
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432

2 Answers2

0

This should do the job

#include <algorithm>
#include <string>
#include <iostream>

void remove_char(std::string s, char r) {
  s.erase( std::remove( s.begin(), s.end(), r), s.end()) ;
  std::cout << s << std::endl;
}

int main()
{
    std::string test = "coffee";
    char r = 'f';
    remove_char(test, r);
    return 0;
}
laker93
  • 498
  • 4
  • 9
  • std::remove: Transforms the range [first,last) into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range. So that 'coffee' -> 'coee??'. The call to 'erase' then removes the end '?' chars – laker93 Feb 16 '18 at 09:14
0

If u want to do this by hand try this:

std::string removeAllOccurrence(string text, char letter)
{
    int off;
    int i;
    i = off = 0;
    string out = "";

    for (i = 0; i < text.size(); i++)
    {
       if (text[i] != letter)
       {
           out += text[i];
       } 
   }

   return out;
 }


int main(void)
{
    string text;
    char letter;
    string newText;

    cout << "Type your text: " << endl;
    cin >> text;
    cout << "Choose the letters to remove: " << endl;
    cin >> letter;


    cout << "your new text is: " + removeAllOccurrence(text, letter) << endl;
    system("pause");
    return 0;
}

As you can see your main function was kinda right. You just need to pass some arguments into the function. Additonally you missed a loop in your remove function. If you use string in your main, why don't use string in yur function? You can just use string there, too

Kind Regards