Link to home
Start Free TrialLog in
Avatar of xneo27
xneo27

asked on

break a string up c++

C++
Okay heres my code:

string line = "120 520 36 4 55 -1"
string strNum;

I want strNum to pull each number at a time by whitespace.
so first time would be 120 next 520 and so on.
How would you suggest going about this?
Avatar of jkr
jkr
Flag of Germany image

The easiest way: Use a 'stringstream', e.g.

#include <sstream>

string line = "120 520 36 4 55 -1"
string strNum;

stringstream ss;
int i = 0;

ss << line;

while(!ss.eof()) {

ss >> strNum;

cout << i << " -> " << strNum << endl;

++i;
}

You could even use an 'int num;', e.g.

#include <sstream>

string line = "120 520 36 4 55 -1"
int num;

stringstream ss;
int i = 0;

ss << line;

while(!ss.eof()) {

ss >> num;

cout << i << " -> " << num << endl;

++i;
}
Avatar of xneo27
xneo27

ASKER

Is there a way to do this without the use of sstream, I cant use it in my current project?
Sure, there are plenty of ways to do that, with 'strtok()' proabaly being the most common one:

#include <string.h>

string line = "120 520 36 4 55 -1"
string strNum;

char seps[]   = " ";
char *token;
char* tmp = strdup(line.c_str());

   /* Establish string and get the first token: */
   token = strtok( tmp, seps );
   while( token != NULL )
   {
      /* While there are tokens in "tmp" */
      strNum = = token;
      cout << strNum << endl;
      /* Get next token: */
      token = strtok( NULL, seps );
   }

free(tmp);
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
if you know how many numbers you are expecting you may use, sscanf:
            
char* line = "120 520 36 4 55 -1"
int N[6],i;
sscanf(line,"%i %i %i %i %i %i",N[0],N[1],N[2],N[3],N[4],N[5]);
for (i=0;i<6;i++){
count << N[i];
}
cout << endl;
Another way is to do like this

void split(const std::string& str,
               std::vector<std::string>& tokens,
               const std::string& delimiters = " ")
{
    std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    std::string::size_type pos = str.find_first_of(delimiters, lastPos);
      
    while (std::string::npos != pos || std::string::npos != lastPos)
    {
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        lastPos = str.find_first_not_of(delimiters, pos);
        pos = str.find_first_of(delimiters, lastPos);
    }
}

...
std::string line = "120 520 36 4 55 -1";
std::vector<std::string> result;
split(line, result);
Avatar of xneo27

ASKER

Thanks that helped alot.