简体   繁体   中英

Create txt Document C++

This code is supposed to create a txt document and put some text in it. However, on lines 10, 25 and 26 (which I'll put a comment next to), I'm getting errors. Please help, and thanks in advance!

#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main()
{
    string textFileName = "SavedPasswords.txt";

    ofstream textFile(textFileName);//10

    textFile << "Password1" << endl << "Password2" << endl;

    textFile.close();

    string directory;
    size_t path = textFileName.rfind("\\");

    if(string::npos != path)
    {
        directory = textFileName.substr(0, path);
    }

    system("cd\\");
    system("cd " + directory);//25
    system("start " + textFileName);//26
}

Here are the errors:

C:\Users\User\Desktop\SavePasswords\main.cpp|10|error: no matching function for call to 'std::basic_ofstream::basic_ofstream(std::string&)'|

C:\Users\User\Desktop\SavePasswords\main.cpp|25|error: cannot convert 'std::basic_string' to 'const char*' for argument '1' to 'int system(const char*)'|

C:\Users\User\Desktop\SavePasswords\main.cpp|26|error: cannot convert 'std::basic_string' to 'const char*' for argument '1' to 'int system(const char*)'|

The constructor for ofstream requires a char* instead of a string . You can easily get a char* from your string with the c_str() member function:

ofstream textFile(textFileName.c_str());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM