Tuffy
Tuffy

Reputation: 197

str.erase(); doesn't work inside a function

I have a code here that ignores comment lines. The thing is, i tried creating a function with what i had so that i can use it later anywhere within my code. But i am encountering a problem. My code:

#include <iostream>
#include <string>

using namespace std;
string comment(string str);

int main ()
{
  string str;
  cout << "Enter the string> ";
  getline( cin, str );
  comment(str);
  cout << str << "\n";

  return 0;
}

string comment(string str)
{

  unsigned found = str.find('#');
  if (found!=std::string::npos)
    str.erase(found);
  else
    return(str);           

  return(str);

}

Sample input:(from keyboard) Enter the string> my name is #comment

output i am getting:

my name is #comment

output i am supposed to get:

my name is

Also if i use the same code without the function, i get the correct answer. And here it is:

#include <iostream>
#include <string>

using namespace std;

int main ()
{
  string str;

  cout << "Enter the string> ";
  getline( cin, str );
  unsigned found = str.find('#');
  if (found!=std::string::npos)
    str.erase(found);


  cout << str << "\n";

  return 0;
}

Upvotes: 0

Views: 118

Answers (1)

stardust
stardust

Reputation: 5988

You have to pass your string by reference

void comment(string& str)
^^^^                 ^^^

OR receive the returned value from the function.

getline( cin, str );
str = comment(str);
^^^

Otherwise the function receives a copy of your string. Any modifications you do str while inside the comment function is not visible in main.

Upvotes: 3

Related Questions