在C++中打开文件

file opening in C++

本文关键字:文件 C++      更新时间:2023-10-16

我对C++相对较新,我想练习文件打开和放入文本,现在我意识到这将是存储登录信息的最糟糕的方式,但这只是我选择模拟它的方式,因为至少它不会是完全随机的。 现在我在除了一个地方之外的所有地方都做得很好,似乎因为我不断收到错误,整个代码都是

#include <iostream>
#include <string>
#include <fstream>
#include <new>
using namespace std;
string login() {
string username, password;
cout << "What is your username?n";
cin >> username;
cout << "What is your password, " << username << endl;
cin >> password;
//Verify info
return username;
}
string signup() {
string username, password, cpass, bio;
do {
cout << "What is your username?n";
cin >> username;
cout << "What is your password?n";
cin >> password;
cout << "Confirm password: ";
cin >> cpass;
cout << "Describe what you like to do:n";
cin >> bio;
} while (password != cpass);
ofstream user = new ofstream();
user("users.txt");
if (user.is_open()) {
//Make sure the program is writing to the end of the file!
user.seekp(0,std::ios::end);
user << username << endl;
user << password << endl;
user << bio << endl;
} else {
cout << "Something went wrong with opening the file!";
}
user.close();
return username;
}
int main() {
string answ;
cout << "Hello, welcome to wewillscamyou.net, are you already signed up?n";
if(answ == "Yes" || answ == "yes") {
string username = login();
} else {
string username = signup();
}
return 0;
}

但是我在这两行上遇到错误,这不是因为拼写错误,我需要帮助,因为这可以在 java 中工作:

ofstream user = new ofstream();
user("users.txt");

C++new中的好友用于创建动态分配的对象,或者您有指针的对象,或者您必须为其分配内存的对象。通常是指向对象的指针。

class A {
public:
A() { }
};
int main () {
A a (); // object (created as value)
A *a = new A(); // notice pointer, I need to allocate memory for it thus I have to use `new`
}

总之,newC++意味着为这个对象分配足够的内存并给我它的地址。因此,要解决您的错误,您有以下几种选择:

ofstream user ("user.txt");

ofstream user;
user = ofstream("users.txt");

ofstream user;
user.open("user.txt");
...
user.close("user.txt");
user("users.txt");

'ofstream' 用于写入文本或二进制文件。而"new"用于分配内存。 要写入文件的末尾,您需要首先以"append"(app(模式打开它。一旦连接到文件,它将自动使用存储驱动器中的内存。

**user.seekp(0,std::ios::end);**

这行代码没有错,但不是必需的。

替换此

ofstream user = new ofstream();
user("users.txt");
if (user.is_open()) {
//Make sure the program is writing to the end of the file!
user.seekp(0,std::ios::end);
user << username << endl;
user << password << endl;
user << bio << endl;
} 

通过这个:-

ofstream user("user.txt",ios::app);
if(user)
{
user << username << endl;
user << password << endl;
user << bio << endl;
}

将文件名传递给ofstream构造函数。 此外,指定要附加到文件 - 无需手动查找。

ofstream user("users.txt", ofstream::app);
if (user)
{
user << username << endl;
user << password << endl;
user << bio << endl;
}
else
{
cout << "Something went wrong with opening the file!";
}