Reading the line from the file



  • We need to write a program that can count the mixed data line from the file. File:

    Ivanov 20 3
    Petrov 18 2
    Sidorov 24 4

    How do you put such data in the mass so that you can then distort?



  • std::istream He can read the data separated by underwear symbols.
    We can set up a record structure for the file.

    struct Record {
        std::string name;
        int a;
        int b;
    };
    

    and read the file std::vector structures

    std::vector<Record> records;
    

    std::ifstream file("file.txt");
    Record tmp;
    while (file >> tmp.name >> tmp.a >> tmp.b) // Читаем поля если файл не закончился.
    records.push_back(tmp);

    After reading, you can check whether the file was read completely.

    if (file.bad()) {
    std::cout << "I/O error\n"; // Пока файл читали, с ним что-то случилось.
    return 1;
    }
    if (!file.eof()) {
    std::cout << "Invalid data\n"; // Не удалось распарсить число.
    return 1;
    }

    And finally toss this vector:

    auto by_name = [](const auto& a, const auto& b) { return a.name < b.name; };
    std::sort(records.begin(), records.end(), by_name);


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2