开发者

Easiest way to get words of one line from istream into a vector?

istream has the >> operator, but it skips new lines like it skips whitespace. How can I get a list of all the words in 1 line only, into a vector (or anything else that's convenien开发者_运维技巧t to use)?


One possibility (though considerably more verbose than I'd like) is:

std::string temp;
std::getline(your_istream, temp);

std::istringstream buffer(temp);
std::vector<std::string> words((std::istream_iterator<std::string>(buffer)),
                                std::istream_iterator<std::string>());


I would suggest using getline to buffer the line into a string, then using a stringstream to parse the contents of that string. For example:

string line;
getline(fileStream, line);

istringstream converter(line);
for (string token; converter >> token; )
    vector.push_back(token);

Be wary of using C string reading functions in C++. The std::string I/O functions are much safer.


You can call istream::getline -- will read into a character array

For example:

char buf[256];
cin.getline(buf, 256);

And if you want to use a streams-compatible accessor for the individual tokens in the line, consider an istringstream

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜