0

How would I split an inputted string such as "one two three four five" into an array. currentyly I have this:

const int SIZE = 5;
string digit[SIZE];

cout << "Enter the five here:";
for(int i = 0; i < SIZE; i++)
{
    cout << i+1 << ")";
    getline(cin, digit[i]);
}

but as it stands, the user has to hit enter every time. How do I get it so when I call digit[1] for the example input above, I get two. Hopefully that makes sense, I would imagine there is some function to do this for you, but if there is really elementary way of doing it, that would probably benefit me best, I'm still learning. thx

3 Answers 3

4

If you want to read words separated by whitespace, you can take advantage of the fact that extracting a string from an input stream will stop at whitespace:

for(int i = 0; i < SIZE; i++)
{
    cout << i+1 << ")";
    cin >> digit[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

perfect - I don't know why that didn't occur to me. Thanks!
0

well if you want to take all the 'five' in a single line you can do that also. and then you can use strtok() to split the string into five strings. see: http://www.cplusplus.com/reference/clibrary/cstring/strtok/

2 Comments

strtok is nasty though. The use of global state can bite you.
strtok_r and strsep are much better than common strtok
0

You also may use getline function with 3 arguments. 3rd is delimiter.

 getline(cin, digit[i], ' ');

Of course, it isn't best way to read input from cin. But you can use such approach for splitting full string, which you've get from user.

1 Comment

that still takes place in the for loop correct? I tried it and the process stalls; it doesn't move on to the next task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.