Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 8th, 2005, 3:54 AM   #1
kiaran
Newbie
 
Join Date: Feb 2005
Posts: 1
Rep Power: 0 kiaran is on a distinguished road
Simple Writing to Files. Newbie Question

Hi guys, this is my first post here. I'm trying desperatly to wrap my head around this file I/O stuff.

I just learnt how to use the new <string> (as opposed to olc char* method). And I'm tring to write some stuff to a file. Here is my entire program. It's really simple but for some reason the line :

//Open output stream to write to file.
ofstream fileOut(input);

This is giving me grief. 'input' is a string that holds the name of the file I want to open. Why is this not working?

Any help will be greatly appreciated.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main ()
{
	//Declare string to house directory of file.
	string input;
	
	//Ask user for file to write to.
	cout << "Please enter file to write to: " << endl;
	cin >> input;

	//Open output stream to write to file.
	ofstream fileOut(input);
	
	//Check to ensure that file was able to be opened.
	if (! fileOut)
	{
		cout << "File " << input << "could not be opened!";
		return -1;
	}

	//Let user know that file was opened sucessfully.
	cout << "File " << input << " was opened.";

	//Write to file.	
	fileOut << "Write this sentance to the file." << endl;
	fileOut << "This should be on a new line.";

	//Close the file.
	fileOut.close();

	return 0;
}
kiaran is offline   Reply With Quote
Old Feb 8th, 2005, 4:22 AM   #2
Berto
Programming Guru
 
Join Date: Aug 2004
Posts: 1,022
Rep Power: 6 Berto is on a distinguished road
Send a message via AIM to Berto Send a message via MSN to Berto
add .c_str() to the end of it.

//Open output stream to write to file.
ofstream fileOut(input.c_str());

which changes the string to a const char which ofstream requires.

explicit ofstream ( const char * filename, openmode mode = out | trunc );

i ran it on my linux box and all works
Berto is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 4:33 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC