C ++从数组复制到数组

时间:2013-05-07 08:14:19

标签: c++ transliteration

我已经尝试了很多针对这个问题的建议解决方案但没有成功。

我有一个长度为1000的const char数组,名为 english_line ,其中包含由空格分隔的单词。该数组被传递给一个函数。根据我们的任务简报,必须使用此功能来实施解决方案。

我想将该数组的内容,一次一个字复制到另一个2D数组中, 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*)'

我花了一天的时间来试图解决这个问题。显然我是一个相对新手。

非常感谢任何提示或建议:)

4 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

注意string和char数组之间的区别。 Char数组是基本数据类型的简单结构,字符串实际上是一个结构更复杂的类。这就是为什么你需要使用字符串的c_str()函数来获取内容为char数组(a.k.a C-string)。

您还应该注意到c_str()在其输出数组的末尾添加了空终止(附加字符'\0')。

答案 2 :(得分:0)

1)循环计数错误(你应该纠正你的数组知识)

2)string :: c_str()将std :: string转换为char *

答案 3 :(得分:0)

您可以使用string代替该数组temp_eng_word。像,

std::string temp_eng_word;

希望能解决您的问题。循环不正确。请检查一下,因为您使用的是二维数组。

相关问题