创建txt文档C ++

时间:2017-03-21 03:29:57

标签: c++

这段代码应该创建一个txt文档并在其中放入一些文本。但是,在第10,25和26行(我会在旁边发表评论)中,我遇到了错误。请帮助,并提前感谢!

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

以下是错误:

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*)'|

1 个答案:

答案 0 :(得分:2)

ofstream的构造函数需要char*而不是string。您可以使用char*成员函数从string轻松获得c_str()

ofstream textFile(textFileName.c_str());