returning a string from a c++ function

2019-08-05 13:45发布

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?

9条回答
\"骚年 ilove
2楼-- · 2019-08-05 14:19

You need to use cin.getline(), cin >> s will only read the first word (delimited by space)

查看更多
男人必须洒脱
3楼-- · 2019-08-05 14:22

This is not an error in your reverse function, but the standard behaviour of istream::operator>>, which only reads until the first whitespace character.

查看更多
戒情不戒烟
4楼-- · 2019-08-05 14:23

The problem is with cin. It stops reading after the first space character is read.

See the "cin and strings" section of this tutorial: http://www.cplusplus.com/doc/tutorial/basic_io/

You can use getline(cin, input); to do what you want.

查看更多
登录 后发表回答