-2

I'm reading from a text file and taking in strings and placing them into two separate arrays. Ex: TargetArr[1] and TypoArr[1] are pairs. I need to be able to look at each letter in the strings so I've tried converting them into char arrays. I want two arrays of char arrays. The code I have is giving me a seg fault, it's coming from when im trying to create the char*[] and convert the strings to char arrays. Not sure what im doing wrong here. Im trying to take the first string in my normal array, make it a char array, then place into my array of char arrays.

if (myfile.is_open()){
    for(int i=0; i<num; i++){
        getline(myfile,targetArr[i]);
        getline(myfile,typoArr[i]);
        getline(myfile,skip);
    }
}

char* targetCArr[num+1];
char* typoCArr[num+1];
for(int i=0; i<num; i++){
    strcpy(targetCArr[i], targetArr[i].c_str());
    strcpy(typoCArr[i], typoArr[i].c_str());
}
R. Row
  • 19
  • 5
  • 1
    you should provide a [mre] and read this: [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 463035818_is_not_an_ai Jul 18 '20 at 15:33
  • [Rubber ducky](https://en.wikipedia.org/wiki/Rubber_duck_debugging) wants to know how large the array at `targetCArr[i]` is in `strcpy(targetCArr[i], targetArr[i].c_str());` – user4581301 Jul 18 '20 at 15:33
  • a string *is* a char array. you do not need to convert anything – 463035818_is_not_an_ai Jul 18 '20 at 15:33

1 Answers1

0

I need to be able to look at each letter in the strings so I've tried converting them into char arrays.

There's no need to do that. You can do, for example:

for (char ch : MyString)
    std::cout << ch;

You can also access individual lements of a std::string by doing:

char ch = MyString [index];

Finally, if you do need a C-style string, you can do:

const char *c_string = MyString.c_str ();
Paul Sanders
  • 24,133
  • 4
  • 26
  • 48