读写包含多列的文件处理c ++

时间:2013-12-13 02:25:41

标签: c++ file-processing ticket-system

让我说我想写和读这个值 假设我想写

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

======================因此,这将是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

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

我想阅读

请输入您的姓名:Janes Rowan

=============================在屏幕上显示=============== ====================

SEAT NAME            CLASS     DEPARTURE TIME  ARRIVAL TIME  FROM    DESTINATION

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

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

如何假设我的编程代码在c ++中?因为我在写作时遇到问题(保存在file.doc中)和用两个单词以上的字符串搜索,并在屏幕上显示整行。而且我也想知道如何删除整行,即 请输入您的姓名以取消门票:Janes Rowan 因此,它将删除整行 我是初学者,因此,希望有人可以帮助我。非常感谢XD!

1 个答案:

答案 0 :(得分:0)

此代码符合您的规范(我认为)。但是你的作业可能不太可能。但也许你可以使用一些想法。

我的输入文件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

我的解决方案,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"; }
}

使用GCC 4.8.2进行测试:g++ -Wall -Wextra -std=c++0x airline.cpp