2014-02-07 80 views
0

我寫了一些代碼,以便將一個字符串(用getline()讀入)轉換爲一個c_strings數組。我遇到的問題是我正在閱讀的項目沒有正確存儲在陣列中。我最初根據它們之間的空格數來解析輸入,然後從那裏繼續輸入,但這也給我帶來了同樣的問題。所以我把我的解析變成了下面的東西,而且我得到了同樣的確切問題,告訴我我的解析工作正常,但是在讀取char *數組中解析內容的過程中,出現了問題。將一個字符串解析爲一個c_strings數組

我的代碼:

int i = 0; 
unsigned inputSize = input.size(); 
unsigned int prev = 0; //prev as in previous space position 
while((prev = input.find(' ', prev)) < inputSize) { 
    ++i; ++prev;   
} 
char* charArray[i + 2]; 
memset(charArray, '\0', i + 2); 
stringstream ss(input); 
string buffer; 
for(int a = 0; ss >> buffer; ++a) { 
    charArray[a] = const_cast<char*>(buffer.c_str()); 
} 

我在做什麼是我指望我輸入的空格數,並使得這個數字+ 2(+2,因爲我需要一個char *數組用NULL結束它)。之後,我解析我的輸入並將其讀入數組中。我使用ss >> buffer作爲我的終止子句,因爲我不會在charArray的分配內存之外分配內存。 buffer.c_str得到了一個const char *,所以我const_cast它以便我將它存儲到char *的(非const)數組中。我使用memset將所有元素設置爲NULL,因爲我知道它將被寫入,除了最後一個元素,我想保持NULL。

測試:

Input: Why hello world 
Output: Junk 

什麼錯我的程序裏面?

+0

怎麼樣的一些意見,告訴使用你的想法的代碼是幹什麼的? – John3136

+0

只是把它放在裏面,但我會把更多的信息放在我認爲解析正在做的事情上。 –

+0

有沒有一個非常好的理由,你不能把輸入到一個stringstream,然後從那裏讀取單詞,比如說,一個'std :: vector '? –

回答

0

僅當存儲在buffer中的字符串未被修改時,由buffer.c_str()返回的指針纔有效。如果您需要修改buffer,則必須事先複製其內容,如果您以後需要舊內容。

0

參見Right way to split an std::string into a vector [duplicate]

Live Example

#include <iostream> 
#include <sstream> 
#include <iterator> 
#include <vector> 
using namespace std; 

int main(int argc, char *argv[]) { 
    std::string input = "Why hello world"; 
    std::stringstream ss(input); 

    std::vector<std::string> vstrings(std::istream_iterator<std::string>(ss), 
     std::istream_iterator<std::string>{}); // C++11 brace syntax 
    char** charArray = new char*[vstrings.size()]; 
    for (unsigned int i = 0; i < vstrings.size(); i++) 
     charArray[i] = (char*)vstrings[i].c_str(); 
    for (unsigned int i = 0; i < vstrings.size(); i++) 
     std::cout << charArray[i] << "\n"; 
    delete[] charArray; 
} 
相關問題