Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c++ - parse string to vector of int

I have a string which contains some number of integers which are delimited with spaces. For example

string myString = "10 15 20 23";

I want to convert it to a vector of integers. So in the example the vector should be equal

vector<int> myNumbers = {10, 15, 20, 23};

How can I do it? Sorry for stupid question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use std::stringstream. You will need to #include <sstream> apart from other includes.

#include <sstream>
#include <vector>
#include <string>

std::string myString = "10 15 20 23";
std::stringstream iss( myString );

int number;
std::vector<int> myNumbers;
while ( iss >> number )
  myNumbers.push_back( number );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...