String not being printed by C++

后端 未结 4 844
自闭症患者
自闭症患者 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: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 
    #include 
    
    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
    

提交回复
热议问题