C++ string array slice
How would I split an inputted string such as "one two three four five" into an array. currentyly I have this:
开发者_如何学Goconst 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
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];
}
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/
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.
精彩评论