Как ввести строку, а затем набор чисел? - PullRequest
0 голосов
/ 17 мая 2018

Здравствуйте, я не совсем понимаю, как можно ввести этот блок из файла.

test_ line_ 10 20 30 40 50 60 70

Джон Доу 40 50 60 70 60 50 30 6090

Генри Смит 60 70 80 90 100 90

Роберт Пейн 70 80 90 60 70 60 80 90 90 90

Сэм Хьюстон 70 70 80 90 70 80 90 80 70 7060

Как собрать первые две строки строки, а затем продолжить собирать до 10 целых чисел.Он должен уметь читать каждую из пяти строк и правильно собирать данные.

1 Ответ

0 голосов
/ 17 мая 2018

Вы можете сделать что-то вроде этого:

#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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...