首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析配置的快速方法

解析配置的快速方法
EN

Stack Overflow用户
提问于 2009-04-06 19:27:57
回答 7查看 439关注 0票数 1

说你有

代码语言:javascript
复制
char *=  "name:454";

解析名称和数字的最佳方法是什么?

std:字符串id等于"name";

双倍d等于454;

STL,请不要提速。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-04-06 19:41:17

代码语言:javascript
复制
#include <iostream>
#include <sstream>
#include <string>

int main() {
  /* output storage */
  std::string id; 
  double d;
  /* convert input to a STL string */
  std::string s("name:454");
  size_t off = std::string::npos;
  /* smart replace: parsing is easier with a space */    
  if ((off = s.find(':')) != std::string::npos) { // error check: all or none 
    s = s.replace(off, 1, 1, ' ');
    std::istringstream iss(s);
    iss >> id >> d;
    std::cout << "id = " << id << " ; d = " << d << '\n';
  }
  return 0;
}

不过,我只需要编写自己的解析器或使用C扫描器函数来提高速度。

票数 1
EN

Stack Overflow用户

发布于 2009-04-06 19:30:25

您希望使用':'作为令牌来查看strtok函数。下面是一个示例:

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] = "name:454";
    char* c = strtok(str, ":");

    while (c != NULL)
    {
        printf("%s\n", c);
        c = strtok(NULL, ":");
    }

    return 0;
}
票数 4
EN

Stack Overflow用户

发布于 2009-04-06 19:34:42

我会使用getline。

示例:http://github.com/lennartkoopmann/scopeport-server/blob/23e3d2e2fede7ced0810deee0aa501a70a4eba40/src/core.cc#L1353

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/722801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档