在使用string.size()时获得无限循环
Getting Infinite loop while using string.size()
#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
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 连接线程时的无限循环
- 为什么这种方法会进入无限循环?
- 由于QTextStream的无限循环
- Qt 在另一个线程中无限循环
- 将regex_search与std::string一起使用时的无限循环
- 在使用string.size()时获得无限循环