c++ - 使用函数从文件输出
问题描述
标题说明了一切
这是我的代码:我有一个名为 House 的类,我在其中定义值。
class HOUSE
{
public:
int id;
string 1;
string 2;
string 3;
int an;
};
template<class Type>
class table
{
public:
vector<Type> V;
//double inceput;
//double sfirsit;
//int comparatii;
//int interschimbari;
public:
table();
void print();
void liniar();
};
template<class Type>
table<Type>::table()
{
ifstream file("file.txt");
ifstream file1("file1.txt");
if (file.fail() || file1.fail())
{
cerr << "Eroare la deschiderea fisierului!" << endl;
_getch();
exit(1);
}
HOUSE* value = new HOUSE;
while (!file.eof() || file1.fail())
{
file >> value->id;
file >> value->tara;
file >> value->brand;
file >> value->culoare;
file >> value->an;
this->V.push_back(*value);
}
file.close();
}
值的打印功能
template<class Type>
void table<Type>::print()
{
cout << endl << setw(50) << "AFISAREA DATELOR" << endl;
cout << setw(5) << "Id" << setw(15) << "1" << setw(20) << "2" << setw(17) << "3" << setw(20) << "an" << endl << endl;
for (int i = 0; i < this->V.size(); i++)
{
cout << setw(5) << this->V.at(i).id << setw(15)
<< this->V.at(i).1<< setw(17)
<< this->V.at(i).2<< setw(17)
<< this->V.at(i).3<< setw(25)
<< this->V.at(i).an << endl;
}
cout << endl << "Dimensiunea tabelului n= " << V.size() << endl;
}
{
file >> value->id;
file >> value->1;
file >> value->2;
file >> value->3;
file >> value->an;
this->V.push_back(*value);
}
file.close();
}
主要是
int main() {
table<MOBILE>* file = new table<MOBILE>();
table<MOBILE>* file1 = new table<MOBILE>();
file ->print();
file1 ->print();
这是所要求的完整代码。需要让它以某种方式打印来自 file1 和 file2 的数据。谢谢
如果调用正确,问题就出在 idk 上。因为文件 ->print();
文件1->打印();都只打印文件中的数据 完全没有错误
解决方案
您的代码有很多错误。但我会忽略这一点,只回答我认为是你的实际问题。
您需要两个table
对象,其中一个从 读取,file.txt
另一个从file1.txt
. 为此,您应该将文件名传递给table::table
构造函数,以便它知道要从哪个文件中读取。像这样
template<class Type>
class table
{
...
public:
table(const char* filename); // constructor takes filename parameter
...
};
template<class Type>
table<Type>::table(const char* filename)
{
ifstream file(filename); // open filename
if (file.fail())
...
int main() {
table<MOBILE>* file = new table<MOBILE>("file.txt"); // read from file.txt
table<MOBILE>* file1 = new table<MOBILE>("file1.txt"); // read from file1.txt
file ->print();
file1 ->print();
}
推荐阅读
- control-m - 控制 M 作业无法调用 peoplesoft 应用程序中的进程
- selenium - Selenium FindElement 按父 div
- java - Gradle android找不到符号上下文
- spring - 为什么会话 bean 在启动时被创建为 Singleton bean,而不能通过创建会话来创建?
- jquery - Bootstrap is-invalid 和 is-valid 无法与 ajax 一起正常工作
- spring - Spring - 当列名与模型中的不同时,本机查询与休眠混合
- centos7 - Haproxy - 无法捕获 URL
- javascript - JavaScript 检测警报并阻止它显示
- login - Typo3 版本 8 登录循环
- android - 调用外部 Intent 时 savedInstanceState 引用了错误的值