Question

#include <iostream>
#include <fstream>
#include <cstring>
#define MAX_CHARS_PER_LINE 512
#define MAX_TOKENS_PER_LINE 20
#define DELIMITER " "
using namespace std;
int main ()
{
    string buf = "PiCalculator(RandGen *randGen, int nPoints) : randGen(randGen), nPoints(nPoints) {";
    string buf1 = buf;

    // parse the line into blank-delimited tokens
    int n = 0;
    string token[MAX_TOKENS_PER_LINE] = {};
    token[0] = strtok(&buf[0], DELIMITER);
    if (token[0].size()) // zero if line is blank
    {
      for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
      {
        token[n] = strtok(0, DELIMITER); // subsequent tokens
        if (token[n].size() == 0) break; // no more tokens
      }
    }
    cout<<endl<<endl;
    // process (print) the tokens
    for (int i = 0; i < n; i++) { // n = #of tokens
       int pos=token[i].find('(');
       if(pos == token[i].size())
            continue;
       else{
        cout<<token[i].substr(0,pos)<<endl;
       }
    }
  return 0;
}

Using this program, I want to sort out the substring just before '(' i.e. PiCalculator. But, when I run the above program, m getting an infinite loop. Unable to sort out the problem. Can anyone help me ??

Was it helpful?

Solution

If you just want whitespace-delimited "words" (or tokens or what you want to call them) from a string, there is some functionality in C++ that can do it for you very simply:

string buf = "PiCalculator(RandGen *randGen, int nPoints) : randGen(randGen), nPoints(nPoints) {";

std::istringstream iss(buf);
std::vector<std::string> tokens;

std::copy(std::istream_iterator<std::string>(iss),
          std::istream_iterator<std::string>(),
          std::back_inserter(tokens));

The above code will copy all (whitespace delimited) "tokens" from the string buf to the vector tokens.

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top