how to insert a string in vector c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Rafsan95
    New Member
    • Feb 2017
    • 1

    how to insert a string in vector c++

    vector <string> mystring;
    mystring.push_b ack("Hello World");
    but when i print after the insertion then i get ("hello") and ("World") as different string.
    i need to get ("Hello World ") As one string..
    pls help me..
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You are not pushing back a string. "Hello world" is a const char*.

    With function overloading, there are many push_back methods and the one used is based on the argument you provide.

    Try:

    Code:
    string obj("Hello World");
    mystring.push_back(obj);
    The push_back with a const char* argument stops pushing when it gets a whitespace byte. Just like it should if this were C. So you push Hello and it stops.

    What is called a string in C is not a string in C++. In C++ a string means a string object. In C++ a C-string is just a \0 terminated array of char.

    Comment

    Working...