c++ - 使用 string.size() 时获取无限循环

标签 c++ string infinite-loop

#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。但是,当我运行上面的程序时,我遇到了一个无限循环。无法解决这个问题。任何人都可以帮助我吗??

最佳答案

如果您只想从字符串中使用空格分隔的“单词”(或标记或您想要的称呼),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 中的所有(以空格分隔的)“标记”复制到 vector tokens 中。

引用资料:

关于c++ - 使用 string.size() 时获取无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23448203/

相关文章:

C++:授予对私有(private)运算符 "passing through"友元类的访问权限,可能吗?

opencv - Haar 级联分类器陷入无限循环,在 2 个状态之间交替。使用 OpenCV (C++)

java - 无法找出为什么我的程序陷入无限循环

Javascript 打字机片段使浏览器没有响应

c++ - 如何将其他 .wo、.so、.a 文件链接到当前 cuda 编译

c++ - 如何实现自动插入隐含占位符的 easy_bind() ? *带有成员指针*

字符串追加不起作用;不断覆盖以前的字符串

c - 简单 C 代码中的段错误(核心转储)

javascript - 与模式匹配或为空字符串的正则表达式

c++ - SDL libsdl1.2-dev