![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Feb 2005
Posts: 1
Rep Power: 0
![]() |
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;
} |
|
|
|
|
|
#2 |
|
Programming Guru
![]() |
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 |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|