Solved

break a string up c++

Posted on 2006-11-02
7
741 Views
Last Modified: 2008-02-01
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?
0
Comment
Question by:xneo27
7 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 17860288
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;
}
0
 

Author Comment

by:xneo27
ID: 17861187
Is there a way to do this without the use of sstream, I cant use it in my current project?
0
 
LVL 86

Expert Comment

by:jkr
ID: 17861286
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);
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 17861685
BTW, another option would be a function like

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int split_text(string strIn, const char cDelim, vector<string>& vResult) {

   int nPos = 0;
   int nCount = 0;
   int nFound;
   string strToken;

   while(1) {

      nFound = strIn.find(cDelim,nPos);

      if (-1 == nFound)  {

        strToken = strIn.substr(nPos,strIn.length() - nPos);
        vResult.push_back(strToken);
        break;
      }

      strToken = strIn.substr(nPos,nFound - nPos);

      nPos = nFound + 1;

      ++nCount;

      vResult.push_back(strToken);

   }

   return nCount;
}

int main () {

  string line = "120 520 36 4 55 -1";
  vector<string> vResult;

   int n = split_text(line,' ',vResult);

   for ( int i = 0; i < n; ++i)
      cout << vResult[i] << endl;
}
0
 
LVL 6

Expert Comment

by:_iskywalker_
ID: 17865226
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;
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17865397
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);
0
 

Author Comment

by:xneo27
ID: 17899141
Thanks that helped alot.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now