#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/