0

So I'm trying to parse an unknown amount of strings from user input in C++ and want to store them in a vector.

I have no idea what to do.

So so say the user enters this: Money Linux fire Computers

I want to be able to take each word and store it into a vector. I originally had something that looked like this, but it failed horribly:

while(in!="")
{
    cin>>in;
    input.push_back(in);
}

Any pointers to where I should start?

user7478
  • 121
  • 1
  • 1
  • 4
  • http://stackoverflow.com/questions/890164/how-can-i-split-a-string-by-a-delimiter-into-an-array –  May 06 '12 at 14:32
  • This is called [string tokenizing (or splitting in some frameworks)](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c). – user7116 May 06 '12 at 14:32
  • "in" is a string variable. It failed because it would not exit out of the loop. – user7478 May 06 '12 at 14:36

2 Answers2

3

Never use input operations outside a conditional check. The canonical way to write your code is:

std::vector<std::string> result;
for (std::string word; std::cin >> word; ) { result.push_back(word); }

(In C++11, you can say result.emplace_back(std::move(word)); instead.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0
string in;
while (cin >> in) {
    input.push_back(in);
}

The >> operator on a stream returns the stream. A std::istream is converted into a boolean by checking whether it is in a good state. If it reaches the end of the input, the expression will be false on the next read.

When the extraction fails, a blank string is not written to the in argument, which is why your loop was not working.

mgiuffrida
  • 3,299
  • 1
  • 26
  • 27
  • Having the EOF bit set doesn't make your stream evaluate to `false`. It's the *fail bit* that does this. – Kerrek SB May 06 '12 at 21:02
  • That makes more sense. The EOF bit is set after the last successful read, and then the next read causes the void* operator to return NULL. Thanks for the correction. – mgiuffrida May 07 '12 at 14:33