2017-03-21 193 views
0

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

#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*)'| 
+0

编译器错误?你收到什么错误?如果你将其添加到你的问题,这将有所帮助。 – Tas

+0

在下面发布了错误。 – onlineone22

+0

什么是10,25和26行? –

回答

2

ofstream的构造函数需要一个char*而不是string。你可以很容易地从你的string一个char*c_str()成员函数:

ofstream textFile(textFileName.c_str()); 
+0

谢谢,错误消失了!我做了什么系统的东西? – onlineone22

+1

@ onlineone22如果你还有其他问题,你应该发布一个新问题。在网站允许的情况下,请务必接受我的回答。 –

+0

该问题是要求修复代码中的所有错误,而不仅仅是像你这样的第一个错误。 – onlineone22