-3

Hello I am confused as to how one would input this block from a file.

test_ line_ 10 20 30 40 50 60 70

John Doe 40 50 60 70 60 50 30 60 90

Henry Smith 60 70 80 90 100 90

Robert Payne 70 80 90 60 70 60 80 90 90 90

Sam Houston 70 70 80 90 70 80 90 80 70 60

How does one collect the first two strings of the line and then continue on to collect up to 10 integers. It should be able to read each of the five lines and collect inputs properly.

  • just type std::cin in favorite search engine – Clonk May 17 '18 at 09:29
  • You could start by checking out the 75 or so answers here: https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string – Bo Persson May 17 '18 at 09:43

1 Answers1

0

You could do something like this:

#include <array>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>



// A structure to hold the input data from the file.
// It has an array of two strings for the names, and
// a vector to hold the numbers (since we don't know
// how many numbers we will get on each line)
struct InputLine
{
    std::array<std::string, 2> names;
    std::vector<int> numbers;
};



int main()
{
    std::ifstream input_file("your_file.txt");
    std::string line;
    // This array will hold the 5 InputLine objects that you read in.
    std::array<InputLine, 5> inputs;
    for (int i = 0; i < 5; i++)
    {
        std::getline(input_file, line);

        // A stringstream can be used to break up the data
        // line into "tokens" of std::string and int for
        // fast and easy processing.
        std::stringstream ss(line);
        InputLine input_line;

        // The for loop reads in the two names
        for (int j = 0; j < 2; j++)
        {
            ss >> input_line.names[j];
        }

        // The while loop reads in as many numbers as exist in the line
        int num;
        while (ss >> num)
        {
            input_line.numbers.push_back(num);
        }

        inputs[i] = input_line;
    }

    return 0;
}
nonremovable
  • 798
  • 1
  • 6
  • 19