-3
我有形式的字符串記號化的字符串在C++
ADD,R1,#分隔值5
我想將其轉換爲三個獨立的變量
string s1 =「ADD」;
int register = 1; [刪除'R'並轉換爲int後]
int literal = 5; [刪除#並轉換成int後]
我試着將它轉換成char *使用strok()函數,但輸出似乎並不緊張
我有形式的字符串記號化的字符串在C++
ADD,R1,#分隔值5
我想將其轉換爲三個獨立的變量
string s1 =「ADD」;
int register = 1; [刪除'R'並轉換爲int後]
int literal = 5; [刪除#並轉換成int後]
我試着將它轉換成char *使用strok()函數,但輸出似乎並不緊張
你想要寫一個解析器。爲了讓我的答案簡單而簡短,我爲你寫了一個非常簡單的解析器。這裏是:
// 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;
}
使用:'std :: string','std :: string :: find()'和'std :: string :: substr'。我也推薦'std :: istringstream'將文本號碼轉換爲內部表示。 –
你可以使用'std :: getline(data_file,text_string,',')'將所有的文本讀到一個逗號中變成一個'text_string' std :: string變量。 –
「int literal = 1; [刪除5並轉換爲int後]」看起來有點奇怪,你丟棄了最後一個'5'。這是不是被','分裂? – Isac