2013-05-07 119 views
0

我已經嘗試了很多針對此問題的建議解決方案,但都沒有成功。C++從數組複製到數組

我有一個長度爲1000的常量字符數組,名爲english_line其中包含由空格分隔的單詞。這個數組被傳遞給一個函數。根據我們的任務摘要,必須使用此功能來實施解決方案。

我想這個數組的內容,一個字一次複製到另一個二維數組,temp_eng_word

char temp_eng_word[2000][50]; 
int j; 

string line = english_line; 
string word; 

istringstream iss(line, istringstream::in); 
while (iss >> word) 
{ 
for (j=0;j<=2000;j++) 
{ 
strcpy(temp_eng_word[j],word); 
} 
} 

`

當我運行它,我得到的錯誤:

cannot convert 'std::string* *{aka std::basic_string(char)}' to 'const char*' for argument '2' to 'char* strcpy(char*, const char*)' 

我花了一天的最好的部分只是試圖做這個問題;顯然我是這個相對的新手。

任何提示或建議,將不勝感激:)

+0

在'for'循環中有條件'j <= 2000',你將循環一次到多次。 – 2013-05-07 08:16:21

+0

我也認爲你的程序中的邏輯有點偏離。現在,將第一個單詞複製到數組的所有2000(或2001,如果不更改您的條件)條目。然後,將第二個單詞複製到數組的所有2000個條目中,覆蓋第一個單詞。等等。爲什麼使用數組數組?爲什麼不是'std :: string'的std :: vector? – 2013-05-07 08:18:53

+0

更好地使用std :: vector with push_back ...然後你不必關心大小 – Mario 2013-05-07 08:19:37

回答

2

使用word.c_str()獲得const char*std::string

同樣的,我不明白你的嵌套循環for的時候,您可能希望而不是做這樣的事情(使用strncpy如果需要最大的49 char複製與補零,並確保該字符串的最後char總是零):

istringstream iss(line, istringstream::in); 
int nWord = 0; 
while((nWord < 2000) && (iss >> word)) 
{ 
    strncpy(temp_eng_word[nWord], word.c_str(), 49); 
    temp_eng_word[nWord][49] = '\0'; /* if it's not already zero-allocated */ 
    ++nWord; 
} 

注意,這將是簡單的使用std::vector<std::string>來存儲你的話:

vector<string> words; 
istringstream iss(line, istringstream::in); 
while(iss >> word) 
{ 
    words.push_back(word); 
} 

其未循環來完成使用std::copy

copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(words)); 
+0

感謝您的建議:) 請參閱鏈接的代碼。 http://pastebin.com/xumTLKU0 我試了你的第一個,在代碼中,我打印到屏幕上進行測試。 它跳過每一行上的第一個單詞。 每隔一行,它會添加上一行的最後一個單詞! 後面的事情也會發生。 對於建議2,當輸出到屏幕上時,它只打印每行中的第一個字: 我會休息一下,並嘗試用一個更清晰的頭腦來理解這一切!感謝提示 - 它給了我希望! :) – user2357438 2013-05-07 17:59:54

0

注串和字符的區別陣列。 char數組是一個基本數據類型的簡單結構,而string實際上是一個具有更復雜結構的類。這就是爲什麼你需要使用字符串的c_str()函數來獲取字符數組(a.k.a C字符串)的內容。

您還應該注意到c_str()在其輸出數組的末尾添加了空終止符(附加字符'\0')。

0

1)循環計數錯誤(請更正陣列知識)

2)字符串:: c_str()轉換的std :: string到char *

0

可以使用string,而不是該數組temp_eng_word。像,

std::string temp_eng_word; 

希望能解決你的問題。循環不正確。請檢查,因爲你正在使用二維數組。

+0

如何將'char *'數組存儲在一個'string'中?我想你的意思是一串「串」或「字符串」的「矢量」。 – zakinster 2013-05-07 09:45:05

+0

如果可以存儲,temp [] [] =「abcdef」;你也可以寫std :: string temp =「abcd」; – 2013-05-07 09:53:22

+0

'temp [] [] =「abcdef」'沒有任何意義。 OP有一個字符串,比如'str [] =「這是一個句子」',並且將它分成多個字符串,比如'result [0] =「this」','result [1] =「is」',等等。所以'result'必須是'char [] []','string []'或者矢量'。 – zakinster 2013-05-07 10:10:48