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

StackOverflow https://stackoverflow.com/questions/18857151

Question

I've gotten my program down so far to getting the file location and file name from the user without a hitch. The problem comes from when I try to create an ofstream object using the file location that is provided by the user. I basically use the append() function in the string library to make the location of the file to be in the standard format of c:\users\user\my documents\"file" which I have working. I've tested the code without the ofstream object and things seem to be fine. So I'm just unsure as to why the ofstream object won't then reference the file location specified by the string variable - filelocation.

At the moment the program should just create a file with Hello in it somewhere, however this isn't happening and the code refuses to compile. I have plans to get user input somewhere further down the line, but this is a small hurdle that I need to overcome before proceeding.

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

Thanks in advance for any help you can provide!

Was it helpful?

Solution

Did you check the argument for std::ofstream constructor? I think it is a const char *.

The constructors are declared as

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

So in your case, you use a std::string as the argument, it should be

   std::ofstream writer(filelocation.c_str());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top