Tokenize string in C ++

I have a line currentLine = "12 23 45"

I need to extract 12, 23, 45 from this line without using Boost libraries. Since I am using string, strtok does not work for me. I tried a number of things that still do not succeed.

Here is my last attempt

while(!inputFile.eof()) while(getline(inputFile,currentLine)) { int countVar=0; int inputArray[10]; char* tokStr; tokStr=(char*)strtok(currentLine.c_str()," "); while(tokstr!=NULL) { inputArray[countVar]=(int)tokstr; countVar++; tokstr=strtok(NULL," "); } } } 

one who does not have strtok

 string currentLine; while(!inputFile.eof()) while(getline(inputFile,currentLine)) { cout<<atoi(currentLine.c_str())<<" "<<endl; int b=0,c=0; for(int i=1;i<currentLine.length();i++) { bool lockOpen=false; if((currentLine[i]==' ') && (lockOpen==false)) { b=i; lockOpen=true; continue; } if((currentLine[i]==' ') && (lockOpen==true)) { c=i; break; } } cout<<b<<"b is"<<" "<<c; } 
+6
source share
4 answers

Try the following:

 #include <sstream> std::string str = "12 34 56"; int a,b,c; std::istringstream stream(str); stream >> a >> b >> c; 

Read a lot about C ++ streams here: http://www.cplusplus.com/reference/iostream/

+9
source
 std::istringstream istr(your_string); std::vector<int> numbers; int number; while (istr >> number) numbers.push_back(number); 

Or, easier (though not very shorter):

 std::vector<int> numbers; std::copy( std::istream_iterator<int>(istr), std::istream_iterator<int>(), std::back_inserter(numbers)); 

(Requires standard headers <sstream> , <algorithm> and <iterator> .)

+5
source

You can also choose a Boost tokenizer ......

 #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; int main(int argc, char** argv) { string str= "India, gold was dear"; char_separator<char> sep(", "); tokenizer< char_separator<char> > tokens(str, sep); BOOST_FOREACH(string t, tokens) { cout << t << "." << endl; } } 
0
source

stringstream and boost::tokenizer are two possibilities. Here is a more explicit solution using string::find and string::substr .

 std::list<std::string> tokenize( std::string const& str, char const token[]) { std::list<std::string> results; std::string::size_type j = 0; while (j < str.length()) { std::string::size_type k = str.find(token, j); if (k == std::string::npos) k = str.length(); results.push_back(str.substr(j, kj)); j = k + 1; } return results; } 

Hope this helps. You can easily turn this into an algorithm that writes tokens to arbitrary containers or accepts a function handle that processes tokens.

0
source

Source: https://habr.com/ru/post/913412/


All Articles