gpt4 book ai didi

c++ - 无法写入文件中的数据,程序C++没有错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:50 24 4
gpt4 key购买 nike

我无法在类中使用这些指针变量向文件写入数据。程序没有错误,但文件中没有写入数据。请有人告诉我我做错了什么。

#include <iostream.h>
#include <fstream.h>

class studentinfo
{
private:/*Creating Private Data Members */
char* VUID;
char* campusID;
char* Studentname;
char* Fathername;

public:
void Storefile();/* Function to Store Data in the File*/
char Display();/*Function to Read and then Display Data from the File*/
studentinfo(char*, char*, char*, char*);/*Constructor to initialize Data Members*/
~studentinfo();
};

/* Constructor Defined Here*/
studentinfo::studentinfo(char* VUID, char* campusID, char* Studentname, char* Fathername)
{
cout << "Parameterized Contructor is Called" << endl << endl;
}

/*Destructor Defined Here*/
studentinfo::~studentinfo()
{
cout << "Destructor Called for destruction of the object" << endl;
system("pause");
}

/*Function to Store Data in the File Defined here*/
void studentinfo::Storefile()
{
ofstream re;
re.open("record.txt");
if(!re)/*Error Checking Mechanism*/
{
cout<<"Error Reading File"<<endl;
}

re << VUID << endl << campusID << endl << Studentname << endl << Fathername << endl;/*Using data members to Store data in the File*/
cout << "All the Data Members are Stored in a File" << endl << endl;
re.close();
}

/*Function to Read and then Display the data in the File is definde here */
char studentinfo::Display()
{
char output[100];/*Array to store and display the data*/
ifstream reh;
reh.open("record.txt");
if(!reh)
{
cout << "Error Reading File" << endl;
}

cout << "Following is My Data" << endl << endl;
while(!reh.eof()){
reh.getline(output, 100, '\n');/*Reading the data and storing it in the 'output' array line by line*/
cout << output << endl;
}

reh.close();
}


/*Main Function starting here*/
main()
{
studentinfo s1("mc130202398", "PMTN08", "Rehan Shahzad Siddiqui","Rizwan Ali Siddiqui");/*Object Created and Initialized by constructor calling*/
s1.Storefile();/*Function Call*/
s1.Display();/*Function Call*/

system("pause");
}

最佳答案

您的构造函数已损坏,所有指针都未分配。在为变量分配一个值之前,您不能使用它的值。

此外,您使用的是什么蹩脚的编译器,或者您有什么警告设置?您的构造函数正在传递指向常量的指针,但它采用非常量指针。那应该肯定会引起警告,指出您对这些指针的处理不当。

  studentinfo s1("mc130202398", "PMTN08", "Rehan Shahzad Siddiqui","Rizwan Ali Siddiqui");/*Object Created and Initialized by constructor calling*/

请注意,您向构造函数传递了一堆常量。

studentinfo::studentinfo(char* VUID, char* campusID, char* Studentname, char* Fathername)

糟糕,但是构造函数采用常规 char* 指针。那么这些指针应该指向什么?

提示:使用像 std::string 这样合理的 C++ 类,这些问题就会神奇地消失。

关于c++ - 无法写入文件中的数据,程序C++没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17314497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com