• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 185
  • Last Modified:

scanning till ,

say I have the following:

this bottle, is, only, a, test

what would be the best way to extract each string that is separated by a comma?... lets say that this line is read line by line from a file
  • 3
1 Solution
E.g something like the following:
#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);
      strToken = strIn.substr(nPos,nFound - nPos);
      nPos = nFound + 1;
   return nCount;
int main () {
  vector<string> vResult;
   int n = split_text("this bottle, is, only, a, test",',',vResult);
   for ( int i = 0; i < n; ++i)
      cout << vResult[i] << endl;

Open in new window

BTW, another option would be 'strtok()', e.g.
// crt_strtok.c
// compile with: /W1
// In this program, a loop uses strtok
// to print all the tokens (separated by commas
// or blanks) in the string named "string".
#include <string.h>
#include <stdio.h>
char string[] = "this bottle, is, only, a, test";
char seps[]   = ",";
char *token;
int main( void )
   printf( "Tokens:\n" );
   // Establish string and get the first token:
   token = strtok( string, seps ); // C4996
   // Note: strtok is deprecated; consider using strtok_s instead
   while( token != NULL )
      // While there are tokens in "string"
      printf( " %s\n", token );
      // Get next token: 
      token = strtok( NULL, seps ); // C4996

Open in new window

kuntilanakAuthor Commented:
oh why have I forgot strtok... thanks if I remember that exists I would have used it first place.. thank you!
You're most welcome ;o)

BTW, don't forget to close your questions once your problem is solved...

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now