Search code examples
c++filevariablesinputinteger

How do I read multiple integers from a file of an unfixed size into multiple variables in c++?


I am trying to take integer data from a file, but I need the data in multiple varaibles. The files are in a format like this:

5 
1 3 10
2 4 15
3 6 8
4 7 3
5 9 12

The number in the first line goes into an int variable (numPros). For all lines after that, the three numbers go into three separate integer variables (id, at, and ct in that order).

This is the code I tried:

// Let user give input file
    cout << "Enter the input file name:  ";
    string in;
    cin >> in;
    cout << "\n\n";

    // Exit program if input file can't be opened
    ifstream inFile;
    inFile.open(in);
    if (!inFile)
    {
        cout << "Input file invalid or failed to open.\n\n";
        return 2;
    }

    // Get the number of processes from the input file
    numPros << inFile.get();

    // Create a list of jobs from the input file
    for (int i = 0; i < numPros; i++)
    {
        timer = 1000;

        int id, at, ct;
        id = inFile.get();
        at = inFile.get();
        ct = inFile.get();
        cout << id << " ";
        if (at < timer)
            timer = at;

        Job j(id, at, ct);
        jobList.push_back(j);
    }

numPros, id, at, and ct are int variables, as mentioned earlier. Job is a class I am using to store the variables together. jobList is a vector, used to hold the jobs. timer is irrelevant to my question, so you can ignore any lines involving it.

I was expecting this to work, but it just seems to create incorrect output. A test cout statement reveals that the numPros variable with the test file above was 0. Doing the came thing with the >> operator instead produced even more incorrect results, the numPros variable is set to 53, and that messes up reading the file (and even for the values it did read, the output was incorrect).


Solution

  • Don't use inFile.get(), that reads in only a single char. Use the >> operator to read in the integers, just as you do with the string filename, eg:

    // Let user give input file
    cout << "Enter the input file name:  ";
    string in;
    cin >> in;
    cout << "\n\n";
    
    // Exit program if input file can't be opened
    ifstream inFile(in);
    if (!inFile)
    {
        cout << "Input file invalid or failed to open.\n\n";
        return 2;
    }
    
    // Get the number of processes from the input file
    inFile >> numPros;
    
    // Create a list of jobs from the input file
    for (int i = 0; i < numPros; i++)
    {
        timer = 1000;
    
        int id, at, ct;
        inFile >> id >> at >> ct;
        cout << id << " ";
        if (at < timer)
            timer = at;
    
        Job j(id, at, ct);
        jobList.push_back(j);
    }