簡體   English   中英

從字符數組中提取字符串

[英]Extracting string from character array

我已經嘗試了memcpy / strncpy / std :: copy但它們似乎都沒有工作導致程序崩潰。

這是我需要做的:

我試圖從用戶輸入中解析爭論。 “message -add 0xAE”

我需要將0xAE部分取為一個整數,以下是一些偽代碼_input將保存完整的字符串“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);
}

編輯:謝謝艾倫!

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 = atoi(_temp);
            CLog->out("\n\n %d",_value);
}

你在找:

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';
    }
}

如果你想使用C ++,那么就要避開各種C函數和所有討厭的內存管理。 我建議閱讀Accelerated C ++ 它確實是學習C ++並實際使用C ++的頂級書籍。 這是沒有C字符串解析例程的問題的另一種解決方案:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM