我在让非常基本的命令提示符文本处理器工作时遇到问题。ofstream() 的问题

I'm having trouble getting a very basic command prompt text processor working. Problems with ofstream()

本文关键字:问题 遇到 ofstream 工作 文本 非常 命令提示符 处理器      更新时间:2023-10-16

到目前为止,我已经让我的程序顺利地从用户那里获取文件位置和文件名。问题来自当我尝试使用用户提供的文件位置创建ofstream对象时。 我基本上使用字符串库中的append()函数使文件的位置采用我正在使用的标准格式c:usersusermy documents"file"。 我已经在没有ofstream对象的情况下测试了代码,事情似乎很好。 所以我只是不确定为什么 ofstream 对象不会引用字符串变量指定的文件位置 - filelocation。

目前,程序应该只是在某处创建一个包含 Hello 的文件,但这并没有发生,代码拒绝编译。我计划在更远的地方获得用户输入,但这是我在继续之前需要克服的一个小障碍。

#include <fstream>
#include <string> 
#include <iostream>
using namespace std ;
int main() 
{
string text = "Hello" ;
string title ;
string usertitle ;
string filelocation = "C:/Users/" ;
string user ;
cout << "Input a title for your file: " ;
cin >> title ;
title.insert(title.length() , ".txt" ) ;
cout << "Your title is: " << title << endl ;
cout << endl << "Input the username associated with your computer (Caps Sensitive): " ;
cin >> user ;
filelocation.append( user ) ;
filelocation.append("/My Documents/") ;
filelocation.append(title) ;
filelocation.insert(0, """) ;
filelocation.insert(filelocation.length() , """ ) ;
cout << "Your chosen file name and location is: " << filelocation << endl ;
ofstream writer( filelocation.c_str() ) ;
if (! writer )
{
    cout << "Error opening file for output" << endl ;
    return -1 ; //Signal an error then exit the program
}
else
{
    writer << text << endl ;
    writer.close() ;
}
return 0 ;
}

提前感谢您提供的任何帮助!

您是否检查了构造函数std::ofstream参数?我认为这是一个const char *.

构造函数声明为

explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);

所以在你的情况下,你使用std::string作为参数,它应该是

   std::ofstream writer(filelocation.c_str());