read and write file processing c++ which contains multiple column

556 views Asked by At

Lets say i want to write and read this value Suppose i want to write

SEAT:
NAME:
CLASS:
DEPR. TIME:
ARRV. TIME:
FROM:
TO:

======================Thus, this is what will be looked like in file.doc=========

SEAT NAME            CLASS     DEPARTURE TIME  ARRIVAL TIME  FROM    DESTINATION

23   Janes Rowan     ECONOMY   11:30           17:30         NY      CHINA

24   Robert Sulliman FIRST     12:30           18:30         LONDON  JAPAN

=================================================================================

And i want to read

Please Enter Your Name: Janes Rowan

=============================display on screen===================================

SEAT NAME            CLASS     DEPARTURE TIME  ARRIVAL TIME  FROM    DESTINATION

23   Janes Rowan     ECONOMY   11:30           17:30         NY      CHINA

================================================================================

How suppose my programming code in c++ will be? Because im facing problem in writing (save in file.doc) and searching of string with two words and more, and to display entire row on screen. And also i do want to know how to delete entire row i.e Please Enter Your Name to Cancel Ticket: Janes Rowan Thus, it will delete entire row I am beginner, thus, hope anyone may help me. Thanks so much XD!

1

There are 1 answers

0
Adam Burry On BEST ANSWER

This code meets your spec as it was given (I think). But it is not likely what you need for your assignment. But perhaps there are some ideas here that you can use.

My input file, db.txt:

SEAT NAME            CLASS     DEPARTURE TIME  ARRIVAL TIME  FROM    DESTINATION
23   Janes Rowan     ECONOMY   11:30           17:30         NY      CHINA
24   Robert Sulliman FIRST     12:30           18:30         LONDON  JAPAN

My solution, airline.cpp:

#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {
  // Read the database.
  std::vector<std::string> database;
  std::string str;
  std::ifstream fin("db.txt");

  while (std::getline(fin, str)) {
    database.push_back(str); }

  // Print the database.
  for (const auto& r : database) {
    std::cout << r << "\n"; }

  // Find.
  std::cout << "Find name: ";
  std::string find_query;
  std::getline(std::cin, find_query);

  std::cout << database[0] << "\n";
  for (const auto& r : database) {
    if (r.find(find_query) != std::string::npos) {
      std::cout << r << "\n"; } }

  // Delete.
  std::cout << "Delete name: ";
  std::string delete_query;
  std::getline(std::cin, delete_query);

  database.erase(std::remove_if(std::begin(database), std::end(database),
      [&](const std::string& s) {
        return s.find(delete_query) != std::string::npos; }),
      std::end(database));

  for (const auto& r : database) {
      std::cout << r << "\n"; }
}

Tested with GCC 4.8.2: g++ -Wall -Wextra -std=c++0x airline.cpp