Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tokenize a String in C++

Tags:

c++

I have a string currentLine="12 23 45"

I need to extract 12, 23, 45 from this string without using Boost libraries. Since i am using string, strtok fails for me. I have tried a number of things still no success.

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," ");
            }
        }
}

the one without 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;    
        }
like image 654
CodeMonkey Avatar asked Apr 17 '12 10:04

CodeMonkey


2 Answers

Try this:

#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/

like image 83
k06a Avatar answered Sep 20 '22 13:09

k06a


std::istringstream istr(your_string);

std::vector<int> numbers;
int number;
while (istr >> number)
    numbers.push_back(number);

Or, simpler (though not really shorter):

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

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

like image 37
Konrad Rudolph Avatar answered Sep 22 '22 13:09

Konrad Rudolph