1

I want to get a line of strings and write every word into it's own variable, so that I can use them for example in if clauses.

I tried:

cin >> var1;  
cin >> var2;
cin >> var3;
cin >> var4;

But this only works if 4 words are entered. I need a way to count the words because I don't know if it's 1,2,3,4 or more words the user enters.

Maybe there is a way with getting the whole string:

getline(cin, string1);

And cut it into words after that. Sorry, I searched a lot but I can't find a way.

I also tried to write the cinbuffer into a variable, but the only way I can do this is with

cin >> varx;

Which is only usefull if there is something in the cinbuffer. If not, the user gets asked for input again.

EDIT: Just found this, works for me. Thanks Anyway! C++ cin whitespace question

Community
  • 1
  • 1
mohrphium
  • 353
  • 1
  • 4
  • 13

3 Answers3

2

You’re on the right track. You can read a line with getline() then use an istringstream to treat that line as a stream of its own. Change this for whatever type T you happen to be using.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

int main(int argc, char** argv) {

    using namespace std;

    vector<T> values;

    {
        string line;
        getline(cin, line);
        istringstream stream(line);

        // Read values into vector.
        copy(istream_iterator<T>(stream), istream_iterator<T>(),
            back_inserter(values));
    }

    cout << "Received " << values.size() << " values:\n";

    // Copy values to output.
    copy(values.begin(), values.end(),
        ostream_iterator<T>(cout, "\n"));

    return 0;

}
Jon Purdy
  • 53,300
  • 8
  • 96
  • 166
0

Writing things to different variables like this is usually the wrong answer. It seems like you want something like an array.

Venge
  • 2,417
  • 16
  • 21
0

sounds like you use getline

http://www.cplusplus.com/reference/string/getline/

then use something like boost split to dump each item into an array

http://www.cplusplus.com/faq/sequences/strings/split/