Search code examples
c++vectorpush-back

String not getting stored in vector?


#include <iostream>
#include <vector>

using namespace std;

int main()
{
    string n, m;
    vector <string> dingdong;

    cin >> n;
    dingdong.push_back(n);
    cin >> m;
    dingdong.push_back(m);

    for (int i = 0; i <2; i ++) {
        cout << dingdong[i];
    }


    return 0;
}

When I run the program and I input "hay sombody there" and hit enter. The program prints "haysombody." So I figured if I increase 'i' to 3 the program will print "haysombodythere" but no, main just crashes. why is this happening and how do I make it so that the entire strings (including the spaces) get stored?


Solution

  • "why is this happening and how do I make it so that the entire strings (including the spaces) get stored?"

    To get more than a single word from the input you should use

    std::getline(cin,n);
    

    instead of

    std::cin >> n;
    

    White spaces are used as delimiters by default, so each call of std::istream's operator>> will just store the text read up to the next white space character.


    See a fully fixed version of your program here please.


    Also if you really want to read into the vector word by word, you use a loop doing so

    string word;
    vector <string> dingdong;
    while(cin >> word) {
        if(word.empty) {
            break;
        }
        dingdong.push_back(word);
    }
    

    and print out like

    for (int i = 0; i < dingdong.size(); ++i) {
        cout << dingdong[i];
    }