简体   繁体   中英

Using a .txt file to input dataset into a vector (potentially more than one of dataset) in C++

I am working on this project for school that uses JNI and C++ together. The java code was given to me, it gets the user to enter 6 different inputs for a data set regarding a zoo animal. At the end it will ask Y or N if you want to add another.

If yes the input will be on a second line, once N is selected it will write to a.txt file and the format will be:

001235 Alita Mammal Wolf 0 0

001234 Bob Mammal Wolf 0 0

(please note there is not an empty line in between the two data)

The code below is what I wrote to open the file and get the inputs into vectors which works successfully for one line of user inputs. I am running into the issue of how to I make this work logically for a potential unknown amount of vectors a user could enter.

void LoadDataFromFile()
{
     /*
            TODO: Write proper code to load data from input file (generated using JNI) into vector/array.
     */

    
    vector<string> zooVector(6);
    int count = 0;
    unsigned int i;

    ifstream inputFile;
    inputFile.open("zoodata.txt");

    if (!inputFile) {
        cerr << "Unable to open file zoodata.txt";
        exit(1);   // call system to stop
    }


    while(count < 6)  {
        for(i = 0; i < 6; ++i) {
            inputFile >> zooVector.at(i);
            count += 1;
        }
    }

The ultimate goal will be to write this to memory for a multi-class inheritance but I am trying to get the inputs to work for the vectors.

You don't need a vector of strings for the different fields of the animal ; you need a struct .

THEN you'd need a vector of those struct s to represent a zoo; it will grow dynamically as you read more lines from your file.

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