Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into an array in C++ [duplicate]

Possible Duplicate:
How to split a string in C++?

I have an input file of data and each line is an entry. in each line each "field" is seperated by a white space " " so I need to split the line by space. other languages have a function called split (C#, PHP etc) but I cant find one for C++. How can I achieve this? Here is my code that gets the lines:

string line;
ifstream in(file);

while(getline(in, line)){

  // Here I would like to split each line and put them into an array

}
like image 840
Ahoura Ghotbi Avatar asked Dec 09 '11 16:12

Ahoura Ghotbi


People also ask

Can you split a string array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can you split a string in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

What is strtok function in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.


1 Answers

#include <sstream>  //for std::istringstream
#include <iterator> //for std::istream_iterator
#include <vector>   //for std::vector

while(std::getline(in, line))
{
    std::istringstream ss(line);
    std::istream_iterator<std::string> begin(ss), end;

    //putting all the tokens in the vector
    std::vector<std::string> arrayTokens(begin, end); 

    //arrayTokens is containing all the tokens - use it!
}

By the way, use qualified-names such as std::getline, std::ifstream like I did. It seems you've written using namespace std somewhere in your code which is considered a bad practice. So don't do that:

  • Why is "using namespace std" considered bad practice?
like image 198
Nawaz Avatar answered Sep 28 '22 21:09

Nawaz