[英]C++ multidimension array storing strings
我希望將例如10個單詞存儲到多維數組中。 這是我的代碼。
char array[10][80]; //store 10 words, each 80 chars in length, get from file
int count = 0;
while ( ifs >> word ){ //while loop get from file input stream <ifstream>
array[count++][0] = word;
}
當我編譯時,出現錯誤。 “從'char *'無效轉換為'char'”。 ifs返回一個char指針。 我怎樣才能成功存入陣列?
因為這是C ++,我會使用STL容器來避免一些char*
限制。 word
將具有類型std::string
, array
將具有類型std::vector<std::string>
並且您將使用push_back
而不是分配。 代碼如下所示:
#include <string>
#include <vector>
std::string word;
std::vector<std::string> array;
while(ifs >> word) {
array.push_back(word);
}
這比char*
更好的原因有幾個:你隱藏動態分配,你有真正可變大小的單詞(最大內存大小),如果你需要超過10個單詞,你沒有任何問題。
編輯 :如評論中所述,如果你有一個支持C ++ 11的編譯器,你可以使用emplace_back
和std::move
,這將移動字符串而不是復制它(單獨emplace_back
將構建字符串emplace_back
。)
您應該定義一個指向我認為的數組的指針,它可以逐個訪問數組塊的每個值(或者您想要的方式)。 您也可以嘗試動態分配。 那些是指針的東西,所以它很容易相提並論。
word是char *(字符串),但是數組[count ++] [0]存儲一個char,你可以改變“array [count ++] [0] = word;” to“strcpy(array [count ++],word);”
char array[10][80]; //store 10 words, each 80 chars in length, get from file
int count = 0;
while ( ifs >> word ){ //while loop get from file input stream <ifstream>
strcpy(array[count++], word);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.