String not being printed by C++

后端 未结 4 845
自闭症患者
自闭症患者 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:05
        std::string str{"reverse me"};
        std::string rev{str.rbegin(), str.rend()};
        //or when you are not interested in the orignal string
        std::reverse(str.begin(), str.end());
    

    Giving the constructur of the reverse string the reversed iterators of your input string gives you the string in reversed order.

    0 讨论(0)
  • 2021-01-16 06:08

    While there are ways to iterate over a std::string and fill the contents of another, the overload of std::basic_string::operator= will replace the content of p (if any) with the content of s in a simple assignment. See std::basic_string::operator=

    For example:

    #include <iostream>
    #include <string>
    
    int main (void) {
    
        std::string s {}, p {};
    
        std::cout << "enter string: ";
        if (getline (std::cin, s)) {
            p = s;  /* simple assignment replaced content of p with content of s */
            std::cout << "string in p : " << p << '\n';
        }
    }
    

    Example Use/Output

    $ ./bin/stringps
    enter string: the string s
    string in p : the string s
    
    0 讨论(0)
  • 2021-01-16 06:13

    string p; doesn't have enough allocated space for directly accessing by something like p[j]

    You can change to initialize p from copying s like below, your code will work.

    string s;
    getline(cin,s);
    string p(s);  // p will be allocated and be the same as s
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题