C++ 条件和文件
我有两个职能:C++ 条件和文件,c++,file,input,C++,File,Input,我有两个职能: load(),该文件正在加载输入.txt文件-该文件包含观看电影所需的电影标题和年龄(e.x.Pulp Fraction-16)以及 addTW(int-id,string-title,int-age),用于添加电影 因此,在添加电影时,您需要键入id、标题和年龄。我想让你不能添加电影,如果你在一定的年龄(e.x.16或其他)。必须从.txt文件中重新添加年龄。基本上与年龄有关,只有头衔 我从未使用过.txt文件。所以我不知道如何开始 #包括 void Client::addT
load()
,该文件正在加载输入.txt
文件-该文件包含观看电影所需的电影标题和年龄(e.x.Pulp Fraction-16)以及
addTW(int-id,string-title,int-age)
,用于添加电影
因此,在添加电影时,您需要键入id、标题和年龄。我想让你不能添加电影,如果你在一定的年龄(e.x.16或其他)。必须从.txt
文件中重新添加年龄。基本上与年龄有关,只有头衔
我从未使用过.txt
文件。所以我不知道如何开始
#包括
void Client::addTW(int-id、字符串标题、int-age)
{
int i,n=tw.size();
对于(i=0;i我不确定,你们班的设计是否合适。这一点你们可以自己去发现
我可以帮助您阅读文件并提取给定标题的年龄:
请参阅:
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();
}
希望这有帮助
使用VS2019和C++17编译和测试您的问题是什么?我很乐意提供帮助,但我应该回答哪个问题?您需要提供更多详细信息。如果您有一个类,如客户端,则需要显示定义。否则无法提供帮助。添加新电影时,我希望函数检查电影标题是否已写入文件-如果是这样的话,它应该读取分配给电影的年龄。如果你添加了15岁的电影,但是电影是从16岁开始的,那么应该有警告或类似的内容
#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;
}
if (age > getAgeFromFile(title))