0

my problem is that when copy another string from a file into a two-dimensional array of char gets an error: "Expression: string subscript out of range"

It needs help, not programmed much advancement so please be as easy as possible explanation and solution to my problem I add the code. Sorry for my english

int ile = 0, rozmiar = 0  ; 
ifstream plik;
string slownik; 
plik.open("C:\\Users\\Mateusz\\Desktop\\Krzyzowka\\slownik.txt"); 
ofstream plik2;
plik2.open("C:\\Users\\Mateusz\\Desktop\\Krzyzowka\\konkretny.txt");
if (plik.good())
{
    cout << "Poprawnie otworzono slownik\n";
    cout << "Ile znakow ma wyraz ?: ";
    cin >> ile; 

    while (plik.good())
    {
        getline(plik, slownik);
        if (slownik.length() == ile)
        {
            plik2 << slownik << endl ;
            rozmiar++;
        }
        //cout << slownik << endl; 
    }
}       
else
    cout << "Nie udalo sie otworzyc slownika\n"; 
plik.close(); 

char **tab = new char*[rozmiar]; 
for (int i = 0; i < rozmiar; i++)
{
    char *nowy = new char[ile]; 
    tab[i] = nowy; 
}
for (int  i = 0; i < rozmiar; i++) 
{
    for (int j = 0; j < ile; j++)
    {
        tab[i][j] = slownik[j];
        cout << tab[i][j];
    }
    cout << endl; 
}
  • 1
    So, a string is something like one-dimensional `char` array. How are you supposed to copy it to a multidimensional array? For what purpose? What are dimensions for? Please add minimal example, preferably in English. (for now you don't even have a `main` function) – Ivan Aksamentov - Drop Feb 16 '15 at 10:17
  • The purpose of this code is not clear at all. Note that `getline(plik, slownik)` can and will fail on the final read that trips eof and exits the loop. What is left in `slownik` *may* be a string that was `ile` length from some prior read, and maybe not. Nothing guarantees the last successful read was that exact length. Once you reach the `for (int j = 0; j < ile; j++)` loop you assume there are `ile` chars in `slownik`. No such guarantee exists.This seems an excessive amount of code for what could be handled with a `std::vector` and a little restriction logic in the file read. – WhozCraig Feb 16 '15 at 10:23
  • 1
    `= slownik[j];` is completely wrong... that means the `j`th+1 character in the current value of the `std::string` `slownik`, which will be the last line you read from the file... if you want to copy the file content into some variables you should do it while reading the file - not afterwards. And using `std::vector` you're massively more likely to get write bug-free code. Meanwhile, change `while (plik.good) { getline(...` to `while (getline(plink, slownik)) { ...`. – Tony Delroy Feb 16 '15 at 10:27
  • 1
    Example of what Tony said: [see it here](http://pastebin.com/vgTedXw9). – WhozCraig Feb 16 '15 at 10:31
  • You should use forward slashes ('/') instead of backslashes ('\') for platform-independence. – набиячлэвэли Feb 17 '15 at 13:09

0 Answers0