0
#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?

Jahaha
  • 29
  • 4

1 Answers1

3

"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];
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • how would I go about it if I was to pass the string 'word' into a class function. I have: string aboutwhat; cout << "Enter subject: " << endl; getline(cin, aboutwhat); person.changeSubject(aboutwhat); cout << person.getSubject(); the program just prints "Enter subject" and ends the program. – Jahaha Feb 22 '15 at 19:31
  • @Jahaha That's a different question. You ask another one. But in general you have some function signature like `void foo(const std::string& word);`, or `void foo(std::string& word)`; depends if you need to change the parameter or not. – πάντα ῥεῖ Feb 22 '15 at 19:35