2012-04-17 12 views
6

I tiene un currentline cadena = "12 23 45"Tokenize una cadena en C++

I necesidad de extraer 12, 23, 45 de esta cadena sin utilizar bibliotecas de Boost. Como estoy usando una cuerda, strtok falla para mí. He intentado una serie de cosas que todavía no tienen éxito.

Aquí es mi último intento

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

el uno sin 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;  
     } 
+0

¿Es ese su código real, con el caso de 'tokstr' y 'tokStr'? Además, http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c –

+0

No informa cómo fallan. ¿Compilan? ¿Se cuelgan? ¿Dan resultados incorrectos? –

+0

USe >> operador con un argumento entero. –

Respuesta

9

Prueba esto:

#include <sstream> 

std::string str = "12 34 56"; 
int a,b,c; 

std::istringstream stream(str); 
stream >> a >> b >> c; 

leído mucho acerca de C++ arroyos aquí: http://www.cplusplus.com/reference/iostream/

+0

error: variable 'std :: istringstream stream' tiene inicializador pero tipo incompleto – CodeMonkey

+0

@ user1290495, '#include ' – hmjd

5
std::istringstream istr(your_string); 

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

O, más simple (aunque no es realmente más corto):

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

(Requiere la encabezados estándar., <algorithm> y <iterator>)

0

También puede optar por tokenizer Boost ......

#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; 
    } 
} 
+1

"sin usar las bibliotecas de Boost" – k06a

0

stringstream y boost::tokenizer son dos posibilidades. Aquí hay una solución más explícita usando string::find y 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, k-j)); 
    j = k + 1; 
    } 
    return results; 
} 

Espero que esto ayude. Puede convertir esto fácilmente en un algoritmo que escribe los tokens en contenedores arbitrarios o toma un control de función que procesa los tokens.