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
文件-该文件具有您需要观看电影的电影标题和年龄(例如,低俗小说-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();
}
最佳答案
我不确定您的类(class)设计是否可以。您可以自己找到。
我可以帮助您阅读文件并提取给定标题的年龄:
请参阅:
#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进行编译和测试
关于c++ - 条件和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59590887/