简体   繁体   中英

Using getline to read from file to a 2d string array

I am trying to read the contents of a text file into a 2D string array, but no matter what I have tried or searched, I can not find a solution. The code is supposed to load a text file separate it into elements by finding horizontal tabs and display the output. When I run the code as is, I receive an error that I found out from searching online, means that I'm trying to manipulate memory I shouldn't be. I'm not asking for the code to be written, just a push in the right direction. Thank you in advance.

this is what I get when I run the program:

0x23fd5c

Process returned -1073741819 (0xC0000005)   execution time : 2.344 s
Press any key to continue.

EDIT:: I have corrected the code so it now functions as it should, but it is not storing the last entry of each line in the text file correctly. I can somehow display the number 100 which is the last entry, but when I try to pass that location or display just playList[0][5] , it says it is equal to the first entry of the next line. Any help would be amazing I posted the current code below.

here is my code:

 #include <iostream>
 #include <string>
 #include <iomanip>
 #include <cstdlib>

 using namespace std;

 void readTextFile( int &Count, string playList[50][5]);
 void userAddition( int &Count, string playList[50][5]);




int main()
{
string decision;
string playList[50][5];
int Count = 0;
readTextFile(Count, playList);

cout << "If you would like to add to the list, Please enter 'Y'. If you would like to exit     
 please enter 'N'. ---->  ";
getline(cin, decision);
if (decision=="y" || decision=="Y")
    userAddition(Count, playList);
else
{
    return(0);
}

return 0;
} // End of Main FN.






void readTextFile( int &Count, string playList[50][5])
{

string inputfield;

ifstream infile("c:\\cTunes.txt", ifstream::in);
    if ( infile.is_open() )
    {
        // File is read.
    }   // end if
    else
    {
        cout << "Error Opening file" << endl;
        return; //Program Closes.
    }  // end else

    cout << setw(30)<<left<< "TITLE"<< setw(10) <<left<<"LENGTH"<<  
      // Outputs a title to          each column that is displayed.
    setw(40)<< left<<"ARTIST"<< setw(40) << left<<"ALBUM"<<
    setw(15) << left <<"GENRE" << setw(5) << left << "RATING" << endl;

getline(infile, inputfield, '\t');    // read until tab
while(! infile.eof())  // loop until file is no longer valid.
 {

        playList[Count][0] = inputfield;
        getline(infile, inputfield, '\t');           // read until tab.

        playList[Count][1] = inputfield;
        getline(infile, inputfield, '\t');             // read until tab.

        playList[Count][2] = inputfield;
        getline(infile, inputfield, '\t');           // read until tab.

        playList[Count][3] = inputfield;
        getline(infile, inputfield, '\t');          // read until tab.

        playList[Count][4] = inputfield;
        getline(infile, inputfield);                // read until end of line.
        playList[Count][5] = inputfield;

    cout << setw(30)<<left<< playList[Count][0] << setw(10) <<left<<playList[Count][1] <<          
    // Output the line number equal to count.
    setw(40)<< left<<playList[Count][2] << setw(40) << left<< playList[Count][3] <<
    setw(15) << left << playList[Count][4] << setw(5) << left << playList[Count][5] <<                     
    endl;

    /*cout <<"Title: " << setw(25)<<left<< playList[Count][0]<<endl;
    cout <<"Length: " << setw(5) <<left<<playList[Count][1] << endl;
    cout <<"Artist: " << setw(50)<< left<<playList[Count][2] << endl;
    cout <<"Album: " << setw(40) << left<< playList[Count][3] << endl;
    cout <<"Genre: " << setw(15) << left << playList[Count][4] << endl;
    cout <<"Rating: " << setw(5) << left << playList[Count][5] << endl<<endl;*/

    Count++;            // Increment counter by 1
    getline(infile, inputfield, '\t'); // read next line until tab.

    }    // end while
 infile.close(); // close the file being read from.
 cout<<endl<<endl<<playList[0][5]<<endl;
 } // End of readTextFile

I believe getline is causing the problem when reading till the end of the line but I'm truly at a loss.

You are using std::string for storing the string, std::ifstream for reading from a file, std::getline for reading words... you should really use std::vector s instead of arrays:

typedef std::vector<std::string> Line;
std::vector<Line> playList;

It will make things easier for you. I also recommend you to change the way you read from a file to:

while(getline(...))
{
    ...
}

But since you are not allowed to use std::vector , your function could look like this:

// reads the content of input file and stores it into playList:
void readTextFile(std::ifstream& infile, std::string playList[][5])
{
    std::string line;
    for (int lineIndex = 0; getline(infile, line); ++lineIndex)
    {
        // skip empty lines:
        if (line.empty()) continue;

        std::string word;
        std::istringstream lineStream(line);
        for (int wordIndex = 0; getline(lineStream, word, '\t'); ++wordIndex)
        {
            // skip empty words:
            if (line.empty()) continue;

            playList[lineIndex][wordIndex] = word;
        }
    }
}

that could be used like this:

std::string playList[19][5];

std::ifstream infile("c:\\Test.txt");
if (infile.is_open())
{
    readTextFile(infile, playList);
    infile.close();
}
else
    std::cout << "Error Opening file" << std::endl;

Also note that cout << playList << endl; outputs the address of the first word. To print all words, you will have to write a loop.

The readTextFile function does not return anything. You need to return a string. If you are getting the error what(): basic_string::_S_construct null not valid then this is your problem. You can avoid similar problems by using -Wall compiler option.

First, note that in the following line:

cout << playList << endl;

you are printing the address of the array, not the contents. you will need a loop to print the contents.

Second, in the following code:

if ( infile.is_open() )
{
   // ok, read in the file
}    // end if
else
{
cout << "Error Opening file" << endl;
//a return statement is missing
}

you need a return statement to avoid reading from a closed stream (which can cause a crash)

Finally, your function does not return anything, so it should either be declared void or return some value (in which there is no sense according to the context).

Hope that helps and good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM