0

Basically, I want the program to allow the user to input say, 2 words, and then split it into a vector. Like, if the user inputs: "Hello world," the program will take the words "Hello," and "world," and store them in a vector. The problem is, I'm not very experienced with vectors, so I have no clue where to start. Here's my code so far:

#include <iostream>
#include <vector>
using namespace std;

void command_case();

string userIn;
int x = 0;

int main()
{
    while(userIn != "QUIT")
    {
        cout << "What shall I do?" << endl;
        cin >> userIn;
        cout << "Your raw command was: " << userIn << endl;
        command_case();
    }
}

void command_case()
{
    vector<char> Search;
    vector<string> command;
    char space = ' ';
    for(int i = 0; i < userIn.size(); ++i)
    {
        if(userIn[i] != space)
        {
            userIn[i] = toupper(userIn[i]);
        }
        if(userIn[i] == space)
        {
            Search.push_back(userIn[i]);
        }
    }
    command.push_back(userIn);
    cout << command[x] << endl;
}

If I input "Hello world," I get this:

What shall I do?
Hello world
Your raw command was: Hello
HELLO
What shall I do?
Your raw command was: world
WORLD

but I would be looking for this:

What shall I do?
Hello world
Your raw command was: Hello world
HELLO WORLD

Could anyone explain to me what I'm doing wrong?

MrMeh
  • 5
  • 2
  • Why vector but not string"? – Gluttton Jun 22 '14 at 10:02
  • possible duplicate of [How to split a string in C++?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) –  Jun 22 '14 at 10:02
  • `cin >> string` will only read one word. I forgot what characters count as word delimiters and how to set them. You can use `getline` instead to read the whole line. – nwp Jun 22 '14 at 10:06
  • `cin >> userIn;` places "hello" in userIn (stops at the first space). The "world" is then the next input for cin. But, yes, this is a duplicate and could easily have been Googled. – Avi Ginsburg Jun 22 '14 at 10:07
  • ...I. Am. Freaking. Stupid. I forgot that getline() even existed. So... now you know how new I am to this stuff. – MrMeh Jun 22 '14 at 10:16
  • Well, you could start from a book. There's plenty of manuals on C++ around. One that I heartily suggest is C++ Primer by Stanley Lippman. Also, Thinking in C++ by Bruce Eckel is an excellent book (and it can be downloaded freely). Both treat the standard IO stream and standard containers in great detail. – Zaphod Beeblebrox Jun 22 '14 at 10:47

1 Answers1

2

Change following code line

cin >> userIn;

To

getline(cin, userIn);
Doonyx
  • 580
  • 3
  • 12