简体   繁体   中英

storing a string letter by letter and printing it

Why won't this program print out "hello" in reverse? It works when I uncomment the line inside the loop. I wanna know the concept behind why the string value isn't getting stored. Thank you!

#include<iostream>

using namespace std;

void reverse(string str) {
        int length = str.length();
        int x = length, i = 0;
        string newString;

        while(x >= 0) {
                newString[i] = str[x-1];
                //cout << newString[i];
                x--;
                i++;
        }

        cout << newString;
}

int main() {
        reverse("hello");

return 0;
}

newString has a size of 0 (constructed with the default constructor), so writing past the end of it with newString[i] = ... causes undefined behavior. Use .resize to resize the string (make it big enough) before writing into it

There are several problems with the program.

For starters you should include the header <string>

#include <string>

because the program uses declarations from this header. It is not necessary that the header <iostream> includes the header <string>

It is much better to declare the function like

void reverse(const string &str);

Otherwise a copy of the original string used as argument is created each time when the function is called.

For the size type the class std::string defines its own unsigned integer type named size_type . It is better to use it or the type specifier auto instead of the type int .

After this declaration

string newString;

newString is empty. So you may not apply the subscript operator. You should either resize the string or reserve enough memory for the new added elements to the string.

Taking this into account the function can be defined the following way.

#include <iostream>
#include <string>

using namespace std;

void reverse( const string &str) {
        auto length = str.length();
        string newString;
        newString.reserve( length );

        for ( auto i = length; i-- != 0;  ) newString += str[i];

        cout << newString << endl;
}

int main() {
        reverse("hello");

        return 0;
}

Take into account that the function could be defined simpler based on the features of the class std::string itself. For example

#include <iostream>
#include <string>

using namespace std;

void reverse( const string &str) {
        string newString( str.rbegin(), str.rend() );

        cout << newString << endl;
}

int main() {
        reverse("hello");

        return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM