gpt4 book ai didi

c++ - C++ 文件打开

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:11 24 4
gpt4 key购买 nike

我是 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++ 中的 Buddy 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`
}

结论 new 在 C++ 中意味着为这个对象分配足够的内存并给我它的地址。因此,要解决您的错误,您有多种选择:

ofstream user ("user.txt");

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

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

关于c++ - C++ 文件打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458158/

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