[英]How to read a HDF5 scalar attribute whose value is an array of variable length char* (i.e. c_strings?)
[英]Parsing a string down into an array of c_strings
我寫了一些代碼,以將一個字符串(用getline()讀入)變成一個c_strings數組。 我遇到的問題是我正在讀取的項目未正確存儲在數組中。 我最初是根據它們之間的空格數來解析輸入的,然后從那里繼續,但這也給我帶來了同樣的問題。 因此,我將解析更改為下面的內容,並且遇到了同樣的確切問題,向我暗示我的解析有效,但是在讀取解析為char *數組的內容的過程中某處出了問題。
我的代碼:
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的char *數組(+2,因為我需要以NULL結尾)。 之后,我解析輸入並將其讀入數組。 我將ss >>緩沖區用作終止子句,因為我最終不會在為charArray分配的內存之外分配內存。 buffer.c_str為我提供了一個const char *,所以我const_cast以便將其存儲到char *的(非const)數組中。 我使用memset將所有元素設置為NULL,因為我知道除了最后一個要保留NULL的元素之外,所有元素都將被覆蓋。
測試:
Input: Why hello world
Output: Junk
我的程序內部出了什么問題?
buffer.c_str()
返回的指針僅在不修改存儲在buffer
的字符串的情況下才有效。 如果需要修改buffer
,則必須事先復制它的內容,如果以后需要舊內容的話。
請參見將std :: string拆分為向量[duplicate]的正確方法 。
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.