Search code examples
c++dynamic-arrays

store the string file into dynamic array


I have three string file that will be stored into dynamic array, but I just try one of three file to test if this succed, so I'll do the same way to handle the three file i have. the goal i'll shown the string that I get from the file to a ListView this my code.

void __fastcall TFrmNewPeta::showDefaultRute() {
    std::string lineDataAwal;
    std::ifstream ifs_Awal;
    int tempIndexAwal = 0;
    ifs_Awal.open("DefaultDataAwal");

        /*counting the line*/
        while(std::getline(ifs_Awal,lineDataAwal)){++tempIndexAwal;}

        /*use dynamic array to stored string*/    
        std::string *s = new std::string[tempIndexAwal];

        for(int dx=0;dx<tempIndexAwal;dx++)
        {
            while(std::getline(ifs_Awal,lineDataAwal))
          s[dx] = lineDataAwal[dx++];
        }

        for(int dex =0;dex<tempIndexAwal;++dex)
        {
           ItemDefult = ListView1->Items->Add();
           ItemDefult->Caption = String(IntToStr(dex + 1));
           ItemDefult->SubItems->Add(s[dex].c_str());
        }
        ifs_Awal.close();
    delete []s;
    s = NULL;
}

there's no errors during compile, but the result ListView just showing the number with this code ItemDefult->Caption = String(IntToStr(dex + 1)); can anyone show me how the best way for i do.


Solution

  • its easier if you use std::vector for dynamic arrays and don't forget to first include the file header with #include<vector>

    void __fastcall TFrmNewPeta::showDefaultRute() {
        std::string lineDataAwal;
        std::ifstream ifs_Awal;
        std::vector<std::string> vec;
        ifs_Awal.open("DefaultDataAwal");
    
       /*get the string of lineDataAwal */
        while(std::getline(ifs_Awal,lineDataAwal))
        { vec.push_back(lineDataAwal);}
    
        for(int dex =0;dex<vec.size();++dex) 
        {
          ItemDefult = ListView1->Items->Add();
          ItemDefult->Caption = String(IntToStr(dex + 1));
          ItemDefult->SubItems->Add(vec.at(dex).c_str()); 
        }
       ifs_Awal.close();
    }
    

    Hope this helps