String not being printed by C++

后端 未结 4 843
自闭症患者
自闭症患者 2021-01-16 05:28

Sorry for the noob question, I\'m a newbie programmer and transitioning from C to C++. I could easily write a program to reverse a string in C the same way with minor change

4条回答
  •  抹茶落季
    2021-01-16 06:21

    To fix your string reverse code you just have to resize the string object p:

    
    int main(){
        std::string s = "hello",
               p;
        p.resize(s.size()); // this was causing your problems, p thought it was size 0
    
        for (int i = s.size() - 1, j = 0; i >= 0; i--, j++)
        {
            p[j] = s[i];
        }
    
        std::cout << p << std::endl;
        return 0;
    }
    
    

    In addition to this, there is no need to find \0 in the string, while it will be there, you can just ask std::string what its size() is.

    On a side note, while std::string probably allocates some memory by default, just assuming it has enough to store whatever you input is going to be undefined behaviour.

提交回复
热议问题