putting a list (.txt) file into a 2D array












0















I'm trying to separate a text file (which has a list of 200 strings) and store each other string (even number and odd number in the list) into a 2D Array.



The text file is ordered in this way (without the numbers):





  1. Alabama


  2. Brighton


  3. Arkansas


  4. Bermuda


  5. Averton

  6. Burmingham


I would like to store it in a 2 dimensional array called strLine[101][2] iterating throughout so the first string in the list is in location [0][0] and the second string of the list is in location [0][1], etc until the file finishes reading and the list becomes organized like this (without the numbers):





  1. Alabama | Brighton


  2. Arkansas | Bermuda


  3. Avertinon | Burmingham


My code outputs the original unsorted list at the moment, i would like to know how to implement the 2d array (with correct syntax) and how to implement an i, j for-loop in the getline() function so it can iterate through each element of the 2D array.



Any help would be greatly appreciated.



My code:



bool LoadListBox()
{

// Declarations
ifstream fInput; // file handle
string strLine[201]; // array of string to hold file data
int index = 0; // index of StrLine array
TCHAR szOutput[50]; // output to listbox,
50 char TCHAR

// File Open Process
fInput.open("data.txt"); // opens the file for read only
if (fInput.is_open())
{
getline( // read a line from the file
fInput, // handle of file to read
strLine[index]); // storage destination and index iterator

while (fInput.good()) // while loop for open file
{
getline( // read line from data file
fInput, // file handle to read
strLine[index++]); // storage destination
}

fInput.close(); // close the file
index = 0; // resets back to start of string

while (strLine[index] != "") // while loop for string not void
{
size_t pReturnValue; // return code for mbstowcs_s

mbstowcs_s( // converts string to TCHAR
&pReturnValue, // return value
szOutput, // destination of the TCHAR
50, // size of the destination TCHAR
strLine[index].c_str(), // source of string as char
50); // max # of chars to copy

SendMessage( // message to a control
hWnd_ListBox, // handle to listbox
LB_ADDSTRING, // append string to listbox
NULL, // window parameter not used
LPARAM(szOutput)); // TCHAR to add

index++; // next element of string array
}
return true; // file loaded okay
}
return false; // file did not load okay
}









share|improve this question















migrated from superuser.com Jan 28 at 4:59


This question came from our site for computer enthusiasts and power users.



















  • I know the string strLine[201] array will have to change into a string strLine[101][2] array in my declarations. In the while(fInput.good( )) loop the strLine[index++] has to change into a for-loop somehow to go through all the elements in the array. Im not sure how to include the syntax for that

    – BuG
    Jan 28 at 4:33











  • Unrelated: while (fInput.good()) tests for validity BEFORE performing the read allowing the read to fail undetected. This leads to the program to, among other things, need a 201 array elements to store a 200 item file. See Why is iostream::eof inside a loop condition considered wrong? for a similar problem

    – user4581301
    Jan 28 at 5:10


















0















I'm trying to separate a text file (which has a list of 200 strings) and store each other string (even number and odd number in the list) into a 2D Array.



The text file is ordered in this way (without the numbers):





  1. Alabama


  2. Brighton


  3. Arkansas


  4. Bermuda


  5. Averton

  6. Burmingham


I would like to store it in a 2 dimensional array called strLine[101][2] iterating throughout so the first string in the list is in location [0][0] and the second string of the list is in location [0][1], etc until the file finishes reading and the list becomes organized like this (without the numbers):





  1. Alabama | Brighton


  2. Arkansas | Bermuda


  3. Avertinon | Burmingham


My code outputs the original unsorted list at the moment, i would like to know how to implement the 2d array (with correct syntax) and how to implement an i, j for-loop in the getline() function so it can iterate through each element of the 2D array.



Any help would be greatly appreciated.



My code:



bool LoadListBox()
{

// Declarations
ifstream fInput; // file handle
string strLine[201]; // array of string to hold file data
int index = 0; // index of StrLine array
TCHAR szOutput[50]; // output to listbox,
50 char TCHAR

// File Open Process
fInput.open("data.txt"); // opens the file for read only
if (fInput.is_open())
{
getline( // read a line from the file
fInput, // handle of file to read
strLine[index]); // storage destination and index iterator

while (fInput.good()) // while loop for open file
{
getline( // read line from data file
fInput, // file handle to read
strLine[index++]); // storage destination
}

fInput.close(); // close the file
index = 0; // resets back to start of string

while (strLine[index] != "") // while loop for string not void
{
size_t pReturnValue; // return code for mbstowcs_s

mbstowcs_s( // converts string to TCHAR
&pReturnValue, // return value
szOutput, // destination of the TCHAR
50, // size of the destination TCHAR
strLine[index].c_str(), // source of string as char
50); // max # of chars to copy

SendMessage( // message to a control
hWnd_ListBox, // handle to listbox
LB_ADDSTRING, // append string to listbox
NULL, // window parameter not used
LPARAM(szOutput)); // TCHAR to add

index++; // next element of string array
}
return true; // file loaded okay
}
return false; // file did not load okay
}









share|improve this question















migrated from superuser.com Jan 28 at 4:59


This question came from our site for computer enthusiasts and power users.



















  • I know the string strLine[201] array will have to change into a string strLine[101][2] array in my declarations. In the while(fInput.good( )) loop the strLine[index++] has to change into a for-loop somehow to go through all the elements in the array. Im not sure how to include the syntax for that

    – BuG
    Jan 28 at 4:33











  • Unrelated: while (fInput.good()) tests for validity BEFORE performing the read allowing the read to fail undetected. This leads to the program to, among other things, need a 201 array elements to store a 200 item file. See Why is iostream::eof inside a loop condition considered wrong? for a similar problem

    – user4581301
    Jan 28 at 5:10
















0












0








0








I'm trying to separate a text file (which has a list of 200 strings) and store each other string (even number and odd number in the list) into a 2D Array.



The text file is ordered in this way (without the numbers):





  1. Alabama


  2. Brighton


  3. Arkansas


  4. Bermuda


  5. Averton

  6. Burmingham


I would like to store it in a 2 dimensional array called strLine[101][2] iterating throughout so the first string in the list is in location [0][0] and the second string of the list is in location [0][1], etc until the file finishes reading and the list becomes organized like this (without the numbers):





  1. Alabama | Brighton


  2. Arkansas | Bermuda


  3. Avertinon | Burmingham


My code outputs the original unsorted list at the moment, i would like to know how to implement the 2d array (with correct syntax) and how to implement an i, j for-loop in the getline() function so it can iterate through each element of the 2D array.



Any help would be greatly appreciated.



My code:



bool LoadListBox()
{

// Declarations
ifstream fInput; // file handle
string strLine[201]; // array of string to hold file data
int index = 0; // index of StrLine array
TCHAR szOutput[50]; // output to listbox,
50 char TCHAR

// File Open Process
fInput.open("data.txt"); // opens the file for read only
if (fInput.is_open())
{
getline( // read a line from the file
fInput, // handle of file to read
strLine[index]); // storage destination and index iterator

while (fInput.good()) // while loop for open file
{
getline( // read line from data file
fInput, // file handle to read
strLine[index++]); // storage destination
}

fInput.close(); // close the file
index = 0; // resets back to start of string

while (strLine[index] != "") // while loop for string not void
{
size_t pReturnValue; // return code for mbstowcs_s

mbstowcs_s( // converts string to TCHAR
&pReturnValue, // return value
szOutput, // destination of the TCHAR
50, // size of the destination TCHAR
strLine[index].c_str(), // source of string as char
50); // max # of chars to copy

SendMessage( // message to a control
hWnd_ListBox, // handle to listbox
LB_ADDSTRING, // append string to listbox
NULL, // window parameter not used
LPARAM(szOutput)); // TCHAR to add

index++; // next element of string array
}
return true; // file loaded okay
}
return false; // file did not load okay
}









share|improve this question
















I'm trying to separate a text file (which has a list of 200 strings) and store each other string (even number and odd number in the list) into a 2D Array.



The text file is ordered in this way (without the numbers):





  1. Alabama


  2. Brighton


  3. Arkansas


  4. Bermuda


  5. Averton

  6. Burmingham


I would like to store it in a 2 dimensional array called strLine[101][2] iterating throughout so the first string in the list is in location [0][0] and the second string of the list is in location [0][1], etc until the file finishes reading and the list becomes organized like this (without the numbers):





  1. Alabama | Brighton


  2. Arkansas | Bermuda


  3. Avertinon | Burmingham


My code outputs the original unsorted list at the moment, i would like to know how to implement the 2d array (with correct syntax) and how to implement an i, j for-loop in the getline() function so it can iterate through each element of the 2D array.



Any help would be greatly appreciated.



My code:



bool LoadListBox()
{

// Declarations
ifstream fInput; // file handle
string strLine[201]; // array of string to hold file data
int index = 0; // index of StrLine array
TCHAR szOutput[50]; // output to listbox,
50 char TCHAR

// File Open Process
fInput.open("data.txt"); // opens the file for read only
if (fInput.is_open())
{
getline( // read a line from the file
fInput, // handle of file to read
strLine[index]); // storage destination and index iterator

while (fInput.good()) // while loop for open file
{
getline( // read line from data file
fInput, // file handle to read
strLine[index++]); // storage destination
}

fInput.close(); // close the file
index = 0; // resets back to start of string

while (strLine[index] != "") // while loop for string not void
{
size_t pReturnValue; // return code for mbstowcs_s

mbstowcs_s( // converts string to TCHAR
&pReturnValue, // return value
szOutput, // destination of the TCHAR
50, // size of the destination TCHAR
strLine[index].c_str(), // source of string as char
50); // max # of chars to copy

SendMessage( // message to a control
hWnd_ListBox, // handle to listbox
LB_ADDSTRING, // append string to listbox
NULL, // window parameter not used
LPARAM(szOutput)); // TCHAR to add

index++; // next element of string array
}
return true; // file loaded okay
}
return false; // file did not load okay
}






c++






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 28 at 5:06









eyllanesc

83.3k103562




83.3k103562










asked Jan 28 at 4:27









BuGBuG

1




1




migrated from superuser.com Jan 28 at 4:59


This question came from our site for computer enthusiasts and power users.









migrated from superuser.com Jan 28 at 4:59


This question came from our site for computer enthusiasts and power users.















  • I know the string strLine[201] array will have to change into a string strLine[101][2] array in my declarations. In the while(fInput.good( )) loop the strLine[index++] has to change into a for-loop somehow to go through all the elements in the array. Im not sure how to include the syntax for that

    – BuG
    Jan 28 at 4:33











  • Unrelated: while (fInput.good()) tests for validity BEFORE performing the read allowing the read to fail undetected. This leads to the program to, among other things, need a 201 array elements to store a 200 item file. See Why is iostream::eof inside a loop condition considered wrong? for a similar problem

    – user4581301
    Jan 28 at 5:10





















  • I know the string strLine[201] array will have to change into a string strLine[101][2] array in my declarations. In the while(fInput.good( )) loop the strLine[index++] has to change into a for-loop somehow to go through all the elements in the array. Im not sure how to include the syntax for that

    – BuG
    Jan 28 at 4:33











  • Unrelated: while (fInput.good()) tests for validity BEFORE performing the read allowing the read to fail undetected. This leads to the program to, among other things, need a 201 array elements to store a 200 item file. See Why is iostream::eof inside a loop condition considered wrong? for a similar problem

    – user4581301
    Jan 28 at 5:10



















I know the string strLine[201] array will have to change into a string strLine[101][2] array in my declarations. In the while(fInput.good( )) loop the strLine[index++] has to change into a for-loop somehow to go through all the elements in the array. Im not sure how to include the syntax for that

– BuG
Jan 28 at 4:33





I know the string strLine[201] array will have to change into a string strLine[101][2] array in my declarations. In the while(fInput.good( )) loop the strLine[index++] has to change into a for-loop somehow to go through all the elements in the array. Im not sure how to include the syntax for that

– BuG
Jan 28 at 4:33













Unrelated: while (fInput.good()) tests for validity BEFORE performing the read allowing the read to fail undetected. This leads to the program to, among other things, need a 201 array elements to store a 200 item file. See Why is iostream::eof inside a loop condition considered wrong? for a similar problem

– user4581301
Jan 28 at 5:10







Unrelated: while (fInput.good()) tests for validity BEFORE performing the read allowing the read to fail undetected. This leads to the program to, among other things, need a 201 array elements to store a 200 item file. See Why is iostream::eof inside a loop condition considered wrong? for a similar problem

– user4581301
Jan 28 at 5:10














1 Answer
1






active

oldest

votes


















0














Step 1



Transform string strLine[201]; to string place[100][2];. Also consider making a



struct place
{
std::string state;
std::string city;
};


because it is a bit more explicit what exactly is being stored. More expressive code is easier to read, generally prevents mistakes (harder to accidentally use strLine[x][2] or something like that), and requires less commenting. Code that comments itself should be a personal goal. The compiler doesn't care, of course, but few people are compilers.



Step 2



Use two separate index variables. Name the first something like num_entries because what it's really doing is counting the number of items in the array.



Step 3



Read two lines into the inner array and test the result of the reads. If they read successfully, increment the index.



while (getline(fInput, place[num_entries][0]) && getline(fInput, place[num_entries][1]))
{
num_entries++;
}


Step 4 (optional clean-up)



Step 2 turns while (strLine[index] != "") into while (index < num_entries)



Replace all of the 50s with a constant. That way you can't change the value and miss a few 50s AND it's easier to infer meaning from a good, descriptive identifier than a raw number.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54395761%2fputting-a-list-txt-file-into-a-2d-array%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Step 1



    Transform string strLine[201]; to string place[100][2];. Also consider making a



    struct place
    {
    std::string state;
    std::string city;
    };


    because it is a bit more explicit what exactly is being stored. More expressive code is easier to read, generally prevents mistakes (harder to accidentally use strLine[x][2] or something like that), and requires less commenting. Code that comments itself should be a personal goal. The compiler doesn't care, of course, but few people are compilers.



    Step 2



    Use two separate index variables. Name the first something like num_entries because what it's really doing is counting the number of items in the array.



    Step 3



    Read two lines into the inner array and test the result of the reads. If they read successfully, increment the index.



    while (getline(fInput, place[num_entries][0]) && getline(fInput, place[num_entries][1]))
    {
    num_entries++;
    }


    Step 4 (optional clean-up)



    Step 2 turns while (strLine[index] != "") into while (index < num_entries)



    Replace all of the 50s with a constant. That way you can't change the value and miss a few 50s AND it's easier to infer meaning from a good, descriptive identifier than a raw number.






    share|improve this answer




























      0














      Step 1



      Transform string strLine[201]; to string place[100][2];. Also consider making a



      struct place
      {
      std::string state;
      std::string city;
      };


      because it is a bit more explicit what exactly is being stored. More expressive code is easier to read, generally prevents mistakes (harder to accidentally use strLine[x][2] or something like that), and requires less commenting. Code that comments itself should be a personal goal. The compiler doesn't care, of course, but few people are compilers.



      Step 2



      Use two separate index variables. Name the first something like num_entries because what it's really doing is counting the number of items in the array.



      Step 3



      Read two lines into the inner array and test the result of the reads. If they read successfully, increment the index.



      while (getline(fInput, place[num_entries][0]) && getline(fInput, place[num_entries][1]))
      {
      num_entries++;
      }


      Step 4 (optional clean-up)



      Step 2 turns while (strLine[index] != "") into while (index < num_entries)



      Replace all of the 50s with a constant. That way you can't change the value and miss a few 50s AND it's easier to infer meaning from a good, descriptive identifier than a raw number.






      share|improve this answer


























        0












        0








        0







        Step 1



        Transform string strLine[201]; to string place[100][2];. Also consider making a



        struct place
        {
        std::string state;
        std::string city;
        };


        because it is a bit more explicit what exactly is being stored. More expressive code is easier to read, generally prevents mistakes (harder to accidentally use strLine[x][2] or something like that), and requires less commenting. Code that comments itself should be a personal goal. The compiler doesn't care, of course, but few people are compilers.



        Step 2



        Use two separate index variables. Name the first something like num_entries because what it's really doing is counting the number of items in the array.



        Step 3



        Read two lines into the inner array and test the result of the reads. If they read successfully, increment the index.



        while (getline(fInput, place[num_entries][0]) && getline(fInput, place[num_entries][1]))
        {
        num_entries++;
        }


        Step 4 (optional clean-up)



        Step 2 turns while (strLine[index] != "") into while (index < num_entries)



        Replace all of the 50s with a constant. That way you can't change the value and miss a few 50s AND it's easier to infer meaning from a good, descriptive identifier than a raw number.






        share|improve this answer













        Step 1



        Transform string strLine[201]; to string place[100][2];. Also consider making a



        struct place
        {
        std::string state;
        std::string city;
        };


        because it is a bit more explicit what exactly is being stored. More expressive code is easier to read, generally prevents mistakes (harder to accidentally use strLine[x][2] or something like that), and requires less commenting. Code that comments itself should be a personal goal. The compiler doesn't care, of course, but few people are compilers.



        Step 2



        Use two separate index variables. Name the first something like num_entries because what it's really doing is counting the number of items in the array.



        Step 3



        Read two lines into the inner array and test the result of the reads. If they read successfully, increment the index.



        while (getline(fInput, place[num_entries][0]) && getline(fInput, place[num_entries][1]))
        {
        num_entries++;
        }


        Step 4 (optional clean-up)



        Step 2 turns while (strLine[index] != "") into while (index < num_entries)



        Replace all of the 50s with a constant. That way you can't change the value and miss a few 50s AND it's easier to infer meaning from a good, descriptive identifier than a raw number.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 28 at 5:36









        user4581301user4581301

        20.8k52033




        20.8k52033
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54395761%2fputting-a-list-txt-file-into-a-2d-array%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Plaza Victoria

            Puebla de Zaragoza

            Musa