2012-08-01 14 views
0

我必須將數據複製成16個字節的集合。我如何以簡單的方式做到這一點? 我想出了下面的算法,但我如何知道是否已添加空終止符?謝謝! :)如何從字符串中複製每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 
} 
+0

你爲什麼不這樣做的所有字符串的std :: string處理?我的意思是,使tempStr成爲一個std :: string,並且只在你做「某些東西」時用它作爲一個char數組。 – 2012-08-01 05:30:37

回答

3

在代碼中,一個字符串結束不添加。您還可以在副本之間跳過一個字符(因爲您的max_len17,而您只複製16個字符)。

我會使用標準庫,而不是提出一個解決方案:

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 
} 
+0

我很困惑這將是更好的方法來使用。 – mister 2012-08-01 05:50:58

+0

@dupdupdup:我認爲這取決於你在做什麼'/做一些東西tempStr',你寧願有一個C字符串或C + +字符串在那一點?就我個人而言,我寧願有一個C++字符串,但在這種情況下,如果您正確地獲得空終止符,C字符串可能會很容易。 – jahhaj 2012-08-01 05:53:01

+0

@jahhaj我最終將需要它在C字符串,因爲我會做加密。所以如果是這樣的話?我會用本傑明的方法? – mister 2012-08-01 06:00:53

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

+0

第一組代碼給了我一個重複的「你好我的名字ishello我的名字是」原始字符串:「你好我的名字是愛麗絲」 – mister 2012-08-01 05:41:19

+0

@dupdupdup:我忘了將'i'添加到'data',再試一次。 – 2012-08-01 05:46:04

+0

哦權力也看到了。謝謝! :) – mister 2012-08-01 05:48:56

相關問題