开发者

Extracting string from character array

开发者 https://www.devze.com 2023-04-11 21:20 出处:网络
I\'ve tried memcpy / strncpy / std::copy but neither of them seem to work resulting the program to crash.

I've tried memcpy / strncpy / std::copy but neither of them seem to work resulting the program to crash.

Here's what i need to do:

I'm trying to parse arguements from user input for instance. "message -add 0xAE"

i need to fetch the 0xAE part into an integer, heres some pseudo-code _input will hold the full string "message -add 0xAE"

if(strstr(_input,"message -add 0x")){
    char* _temp;
    std::copy(strlen("message -add 0x"),strlen("message -add 0x")+(strlen(_input)-strlen("message -add  0x")),_temp);
    /* or */
    memcpy(_temp,_input+strlen("message -add 0x"),strlen(_input)-strlen("message -add 0x"));
    int _value = (int)_temp;
    CLog->out("\n\n %d",_value);
}

Edit: Thanks Alan!

if(strstr(_input,"message -add 0x")){
            char* _temp = new char[strlen(_input)-strlen("message -add 0x")];
            memcpy(_temp,_input+strlen("message -add 0x"),strlen(_input)-strlen("message -add 0x"));
            int _value = 开发者_StackOverflowatoi(_temp);
            CLog->out("\n\n %d",_value);
}


Are you looking for:

int value = 0;
char c;
for(int i = strlen("message -add 0x"); c = *(_input + i); i++) {
    value <<= 4;
    if(c > '0' && c <= '9') {
        // A digit
        value += c - '0';
    } else if(c >= 'A' && c < 'G') {
        // Hexadecimal
        value += 10 + c - 'A';
    }
}

?


If you want to use C++, then steer clear of the various C functions and all of that nasty memory management. I would recommend reading Accelerated C++. It really is a top-notch book for learning C++ and actually using C++. Here's another solution to your problem without the C string parsing routines:

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>


int
main()
{
    std::string const TARGET("message -add 0x");
    char const _input[] = "message -add 0xAE23";

    std::string input(_input);
    std::string::size_type offset = input.find(TARGET);
    if (offset != std::string::npos) {
        std::istringstream iss(input);
        iss.seekg(offset + TARGET.length());
        unsigned long value;
        iss >> std::hex >> value;
        std::cout << "VALUE<" << value << ">" << std::endl;
    }

    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号