I'm a beginner and I've been going through a book on C++, and I'm on a chapter on functions. I wrote one to reverse a string, return a copy of it to main and output it.
string reverseInput(string input);
int main()
{
string input="Test string";
//cin>>input;
cout<<reverseInput(input);
return 0;
}
string reverseInput(string input)
{
string reverse=input;
int count=input.length();
for(int i=input.length(), j=0; i>=0; i--, j++){
reverse[j]=input[i-1];
}
return reverse;
}
The above seems to work. The problem occurs when I change the following code:
string input="Test string";
to:
string input;
cin>>input;
After this change, the reverse function returns only the reverse of the first inputted word, instead of the entire string. I can't figure out where I am going wrong.
Lastly, is there a more elegant way of doing this by using references, without making a copy of the input, so that the input variable itself is modified?
Inplace reverse function was already answered in detail here:
How do you reverse a string in place in C or C++?
As for your question about references and copying:
You pass your argument as reference, and you return a reference. No copying involved, and in a body, you don't define any new string, you are working on the same instance.
Try this:
istream& getline ( istream& is, string& str );
It takes an entire line from a stream you give, e.g.
cin
and saves it into astring
variable. Example:cin.getline(...)
would work on C-style character buffers.cin >> input
reads a word. To read an entire line you should use getlineA debugger is very useful in this cases, you can just see the values of the variables stepping through the program.
A simple cout << input; would have helped you too but if you still don't have a good IDE with integrate debugger I would suggest you to use one. Eclipse is good and open source. Visual studio 2010 express is good and free if you are on windows.
The problem with your code is that
std::cin
reads character till it encounters a character for whichstd::isspace(c)
returnstrue
. So spaces and newlines are all such characters which returnstrue
when passing tostd::isspace
.So what you need basically is,
std::getline
:cin>>input;
reads a word, not a line.Use e.g.
getline(cin, input);
to read a line