用C ++打开文件

时间:2018-05-22 00:23:31

标签: c++ variables fstream

我对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");

3 个答案:

答案 0 :(得分:1)

将文件名传递给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!";
}

答案 1 :(得分:1)

&#39; ofstream的&#39;用于写入文本或二进制文件。虽然&#39; new&#39;用于分配内存。 要在文件末尾写入,您需要先在“附加”(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;
}

答案 2 :(得分:1)

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`
}

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

ofstream user ("user.txt");

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

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