Solved

break a string up c++

Posted on 2006-11-02
7
745 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Fast, free, private online code repository / editor 7 113
thread-safe code in c++ 2 122
computer science syllabus 3 103
designing in object programming 12 110
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

730 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