Domanda

I have tried alot of suggestion solutions to this problem with no success.

I have a const char array, of length 1000, called english_line which containing words seperated by whitespace. This array is passed into a function. This function must be used to implemented the solution as per our assignment brief.

I want to copy the contents of that array, one word at a time into another 2D array, 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);
 }
}

`

When I run this, I get the error:

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

I have spent the best part of a day just trying to do this problem; obviously I am a relative novice at this.

Any tips or suggestions would be greatly appreciated :)

È stato utile?

Soluzione

Use word.c_str() to get a const char* out of the std::string

Also, I don't understand the point of your nested for loop, you may want to do something like this instead (using strncpy to copy a maximum of 49 char with zero-padding if needed, and ensure the last char of the string is always zero) :

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;
}

Note that it would be simpler to use std::vector<std::string> to store your words :

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

Which could be done without a loop using std::copy :

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

Altri suggerimenti

1) Loop count wrong (You should correct your array knowledge)

2) string::c_str() to convert std::string to char*

Note the difference between string and char array. Char array is a simple structure of basic data type and string is actually a class having more complicated structure. That's why you need to use c_str() function of the string to get the content as char array (a.k.a C-string).

You should also notice that c_str() adds null termination (additional character '\0') in the end of its output array.

You can use string instead of that array temp_eng_word. Like,

std::string temp_eng_word;

Hope that will fix your problem. And the loop is not correct. Please check that, as you are using two dimensional array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top