在使用string.size()时获得无限循环

Getting Infinite loop while using string.size()

本文关键字:无限循环 string size      更新时间:2023-10-16
#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;
}

使用这个程序,我想对'('即PiCalculator前面的子字符串进行排序。但是,当我运行上面的程序时,我得到了一个无限循环。无法解决问题。有人能帮帮我吗?

如果您只想从字符串中获得以空格分隔的"words"(或令牌或您想要称呼它们的东西),c++中有一些功能可以非常简单地为您完成:

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));

以上代码将复制所有(以空格分隔)从字符串buf到向量tokens的"token"

引用:

  • std::istringstream
  • std::copy
  • std::istream_iterator
  • std::back_inserter