0

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;
}
4

1 回答 1

3

你必须通过引用传递你的字符串

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

或从函数接收返回值。

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

否则,该函数会收到您的字符串的副本。您strcomment函数内部所做的任何修改在main.

于 2013-05-16T21:50:59.200 回答