首页 > 解决方案 > 条件和文件

问题描述

class Client
{
    public:
    Client(int id, string title, int age):
    ~Client();
    void addTW(int id, string title, int age);
    int getID() const {return id;}
    string getTitle() const {return title;}
    int getAge() const {return age;}
    private:
    int id; 
    string title;
    int age;
 };

我有两个功能:

load(),它正在加载输入.txt文件 - 文件具有您观看电影所需的电影标题和年龄(例如 Pulp Fiction - 16)和

addTW(int id, string title, int age),其中添加了电影。

因此,在添加电影时,您需要输入 id、标题和年龄。如果您未满一定年龄(例如 16 岁或其他年龄),我想让您无法添加电影。.txt年龄必须从文件中重新添加。基本上年龄与头衔有关,而且只有头衔。

我从来没有使用过.txt文件。所以我不知道如何开始。


    #include <fstream>
void Client::addTW(int id, string title, int age)
{
   int i, n = tw.size();
   for(i = 0;i<n;i++)
   {
      ToWatch* newTW = new ToWatch(id, title, age);
      tw.push_back(newTW);
      return;
   }
}

void Client::load()
{
   ifstream input;
   input.open("input.txt");
   if(input.fail())
   { cout<<"Failure"<<endl;}
   else
   {
       string s;
       while(input>>s)
       {
           cout<<s<<" ";
       }
   }
   input.close();
}

标签: c++fileinput

解决方案


我不确定,如果你的类的设计是好的。这个你可以自己找出来。

我可以帮助您阅读文件并提取给定标题的年龄:

请参见:

#include <iostream>
#include <fstream>
#include <string>

unsigned int getAgeFromFile(const std::string& title) {

    // We set a default age of 0. So, if we cannot find the title in the list, then everybody can look it
    unsigned int resultingAge{ 0 };

    // Define an ifstream variable. Use its constructor, to open the file, then check, if open was ok
    if (std::ifstream fileMovies("input.txt"); fileMovies) {

        // Read all lines in the text file in a loop with std::getline. std::getline will return false,
        // if we are at end-of-file or in case of some other error. Then the loop will stop
        for (std::string line{}; std::getline(fileMovies, line); ) {

            // So, now we have a line from the file in tour "line" variable.
            // Check, if the searched title is in it
            if (line.find(title) != std::string::npos) {

                // Ok, we found the title in this line. Now, we need to extract the age.
                // It is at the end of the line and separated by a space. So, search from the end of the line for a space
                if (size_t pos{ line.rfind(' ') }; pos != std::string::npos) {
                    // We found a space. Now, convert the number.
                    resultingAge = std::stoul(line.substr(pos));
                }
            }
        }
    }
    // return result or default value, if not found
    return resultingAge;
}

在您的addTW函数中,您需要在 push_back.

if (age > getAgeFromFile(title))

希望这可以帮助。

用VS2019和C++17编译测试


推荐阅读