0

データを16バイトのセットにコピーする必要があります。簡単な方法でそれを行うにはどうすればよいですか?以下のアルゴリズムを思いついたのですが、ヌルターミネータが追加されているかどうかをどうやって知ることができますか?ありがとう!:)

std::string input
//get message to send to client
std::cout << "Enter message to send (type /q to quit) : ";  
getline(std::cin, input);
input += '\n';

const char *data = input.c_str();

len = strlen(data)+1;
int max_len =17;

//split msg into 16 bytes
for(int i = 0; i < len ; i+=max_len)
{
    char tempStr[max_len];
    //get next 16 bytes of msg and store
    for(int j = 0; j < max_len ; j++)
    {           
        tempStr[j] = data[j+i];
    }//end of for loop

     //Do some stuff to tempStr
}
4

2 に答える 2

3

コードでは、文字列ターミネータは追加されていません。また、コピーの間に1文字スキップします(文字をコピーするだけの場合とmax_len同じように)。1716

代わりに、標準ライブラリを使用したソリューションを提案します。

std::string::const_iterator pos = input.begin();

while (pos < input.end())
{
    // Create a temporary string containing 17 "null" characters
    char tmp[17] = {'\0' };

    // Make sure we co no copy beyond the end
    std::string::const_iterator end =
        (pos + 16 < input.end() ? pos + 16 : input.end());

    // Do the actual copying
    std::copy(pos, end, tmp);

    // Advance position
    pos += 16;

    // Use the string in 'tmp', it is properly terminated
}
于 2012-08-01T05:33:56.727 に答える
1
const char* data = input.c_str();
int len = input.size(); // don't add 1
for (int i=0; i<len; i+=16)
{
    char tempStr[17];
    tempStr[16] = 0;
    strncpy(tempStr, data + i, 16);

    // Do some stuff to tempStr
}

tempStrで実際に行うことによっては、コピーをまったく行わないソリューションが存在する場合があります。

for (int i=0; i<len; i+=16)
{
    llvm::StringRef sref(data + i, data + std::min(i+16,len));

    // use sref
}

llvm :: StringRef

于 2012-08-01T05:27:53.483 に答える