对字符串进行标记以分隔C ++中的值

时间:2017-10-11 22:56:57

标签: c++

我有一个表格

的字符串
  

ADD,R1,#5

我想将其转换为三个单独的变量

  

string s1 =“ADD”;

     

int register = 1; [删除'R'并转换为int]后

     

int literal = 5; [删除#并转换为int]

我尝试使用strok()函数将其转换为char *,但输出看起来并不紧张

1 个答案:

答案 0 :(得分:0)

你想写一个解析器。为了让我的答案变得简单而简短,我为你写了一个非常简单的解析器。这是它:

// Written by 'imerso' for a StackOverflow answer

#include <string.h>
#include <stdio.h>
#include <stdlib.h>


// Extract next substring from current pointer
// to next separator or end of string
char* NextToken(char** cmd, const char* sep)
{
    char* pStart = *cmd;
    char* pPos = strstr(*cmd, sep);

    if (!pPos)
    {
        // no more separators, return the entire string
        return *cmd;
    }

    // return from the start of the string up to the separator
    *pPos = 0;
    *cmd = pPos+1;
    return pStart;
}


// Warning: this is a very simple and minimal parser, meant only as an example,
// so be careful. It only parses the simple commands without any spaces etc.
// I suggest you to try with ADD,R1,#5 similar commands only.
// A full parser *can* be created from here, but I wanted to keep it really simple
// for the answer to be short.
int main(int argc, char* argv[])
{
    // requires the command as a parameter
    if (argc != 2)
    {
        printf("Syntax: %s ADD,R1,#5\n", argv[0]);
        return -1;
    }

    // the command will be split into these
    char token[32];
    int reg = 0;
    int lit = 0;

    // create a modificable copy of the command-line
    char cmd[64];
    strncpy(cmd, argv[1], 64);
    printf("Command-Line: %s\n", cmd);

    // scan the three command-parameters
    char* pPos = cmd;
    strncpy(token, NextToken(&pPos, ","), 32);
    reg = atoi(NextToken(&pPos, ",")+1);
    lit = atoi(NextToken(&pPos, ",")+1);

    // show
    printf("Command: %s, register: %u, literal: %u\n", token, reg, lit);

    // done.
    return 0;
}