c++ - 条件和文件
问题描述
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();
}
解决方案
我不确定,如果你的类的设计是好的。这个你可以自己找出来。
我可以帮助您阅读文件并提取给定标题的年龄:
请参见:
#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编译测试
推荐阅读
- excel - 使用通配符从文件夹中获取文件名
- python - Python。我想以交互方式将我的猜谜游戏的输入限制为整数
- google-maps - 选择地址时谷歌地图设置文本字段值
- java - DRL 文件的方法以启用强制班次计数和连续/实时计划
- c++ - 有没有办法清除getline中的输入?
- python - 在 Siesta 库的 python/fortran 上编译时出错(错误:行被截断)
- c - 如何使用 WinAPI 中的 EN_PROTECT 部分保护富编辑控件中的字符?
- ruby-on-rails - Rails 4 ActiveRecord group_by 和嵌套循环
- xcode - SwiftUI MVVM @Environment Breaks
- python - 为什么通过 Python 上传文件时 Google Drive API 会损坏我的文件扩展名?