Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

break a string up c++

Posted on 2006-11-02
7
Medium Priority
?
749 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
Technology Partners: 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 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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 goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
Suggested Courses

618 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