Just to get one thing straight: When you do:
string blah("Hello!!");
Is new memory allocated and is "Hello!!" copied, yes?
Yes. "Hello!" is a literal string, so the program allocates and
initializes it in "read only" memory somewhere. When the program reaches
the declaration of 'blah', it invokes the constructor for class 'string'
and passes a pointer to the literal string as an argument. The
constructor then allocates memory to hold the string data, and copies the
literal string into it.
string& RemoveUnnecessarySpaces(string& input_string)
{ [snip code]
}
Your function works fine for me when I use it as below, after inserting a
'return' statement.
#include <iostream>
#include <string>
using namespace std;
string& RemoveUnnecessarySpaces(string& input_string)
{
// snip your code
return input_string;
}
int main ()
{
cout << "gimme a string:" << endl;
string line;
getline (cin, line);
cout << "You entered '" << line << "'." << endl;
cout << "Stripping extra spaces..." << endl;
string stripped = RemoveUnnecessarySpaces (line);
cout << "Result is '" << stripped << "'." << endl;
return 0;
}
Sample output:
gimme a string:
fee fie foe fum
You entered ' fee fie foe fum '.
Stripping extra spaces...
Result is 'fee fie foe fum'.
Original is now 'fee fie foe fum'.
Note that your function also leaves the stripped string in the input
parameter, as you can see if you output the contents of 'line' after the
function call. In fact, your function is returning a reference to 'line',
in this example; then the main function copies the (modified) contents of
'line' into 'stripped'. Is this really the way you want it?
I think most programmers would either make this a void function which
returns the "stripped" string via a modified reference parameter only:
#include <iostream>
#include <string>
using namespace std;
void RemoveUnnecessarySpaces(string& input_string)
{
// snip; no 'return' statement
}
int main ()
{
cout << "gimme a string:" << endl;
string line;
getline (cin, line);
cout << "You entered '" << line << "'." << endl;
cout << "Stripping extra spaces..." << endl;
RemoveUnnecessarySpaces (line);
cout << "Result is '" << line << "'." << endl;
return 0;
}
Or pass the string by value, which leaves the original version unmodified,
and return the new string by value (can't use a reference here because the
new string is a local variable inside the function):
#include <iostream>
#include <string>
using namespace std;
string RemoveUnnecessarySpaces(string input_string)
{
// snip
return input_string;
}
int main ()
{
cout << "gimme a string:" << endl;
string line;
getline (cin, line);
cout << "You entered '" << line << "'." << endl;
cout << "Stripping extra spaces..." << endl;
string stripped = RemoveUnnecessarySpaces (line);
cout << "Result is '" << stripped << "'." << endl;
cout << "Original is still '" << line << "'." << endl;
return 0;
}
Of course, this version does two string copies, which may affect your
program's performance.