简体   繁体   中英

How do I read an input file line by line into multiple arrays of different types

As an example input file:

02-03-2004,13045634
03-02-2004,16782930

I'm having trouble coming up with code that can read in inputs into different arrays properly. My most recent attempt is this:

int i = 0;
if(inputFile.is_open()){
     while(!inputFile.eof() && i < arraySize){
          getline(inputFile, line, ',');
          date[i] = line;     //array of type string
          getline(inputFile, line, ',');
          deaths[i] = line;     //array of type int
          //...
          i++;
     }
}

I'm struggling to figure out how exactly I'm supposed to move through the input file with the delimiter of ',' while storing everything correctly.

The array I'm trying to read into is a dynamic array, where I already have a function made that determines the size of the array through getline

I also have to keep the ints as ints because there are functions that need to do calculations with them

As a side note, I can't use vectors for this because they haven't been covered in my class yet

You can do this easily enough, assuming your input is invariably two items on a line, comma-separated:

std::vector<std::string> dates;
std::vector<std::string> IDs;

std::ifstream f( ... );
std::string date, ID;
while (getline( f, date, ',' ) and getline( f, ID ))
{
  dates.push_back( date );
  IDs.push_back( ID );
}

I also wholly recommend Some programmer dude ’s comments above: get each line of input and then use a std::istringstream to parse it, and use a struct for your data:

struct Ticket
{
  std::string date;
  std::string job_number;
};

std::vector<Ticket> tickets;

And so on.

Ok, I got it working now. It seems like the problem wasn't the way I was getting the input, but rather the fact that the loop wouldn't run. Turns out that I had to close the file when I was done using it in a different function and then reopen it when it came to the input reading function to reset the while loop's condition.

I got the input working properly with this code after I fixed the loop issue:

void getArrayData(ifstream &inputFile, string *&date, int *&death, string *& state, int *&cas, int arrSize, int *&fip) {
    string temp;
    int k = 0;
    while(getline(inputFile, temp)){
        string workingLine;
        stringstream ss(temp);
        getline(ss, date[k], ',');
        getline(ss, state[k], ',');
        getline(ss, workingLine, ',');
        fip[k] = stoi(workingLine);
        getline(ss, workingLine, ',');
        cas[k] = stoi(workingLine);
        getline(ss, workingLine, ',');
        death[k] = stoi(workingLine);
        k++;
        
    }
    inputFile.close();
}

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