Mojo Mojo - 3 months ago 11
C++ Question

writing a file in c++ with Xcode and running with terminal

I'm very new to programming and i bought myself a self help book but the book is designed for windows. I've mostly been able to translate so far but i'm stumped on writing/appending files and running them through terminal. I was wondering if someone could translate these lines for me. these lines are what I'm told to type in command prompt/terminal.

C:\MyPrograms> c++ write.cpp -o write.exe

C:\MyPrograms> write

#include <stdio.h>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
string poem = "\n\tI never saw a man who looked" ;
poem.append("\n\tWith such a wistful eye") ;
poem.append("\n\tUpon that little tent of blue") ;
poem.append("\n\tWhich prisoners call the sky") ;

ofstream writer("poem.txt") ;

if (! writer)
{
cout << "Error opening file for output" << endl ;
return -1 ; //signal an error then exit the program.
}

writer << poem << endl ; // write output
writer.close() ; // close filestream.

return 0 ;
}


This is the program i am trying to run named write.cpp please help thanks!

Answer

On OS X, the first line in Terminal would be:

g++ write.cpp -o write

The second line would be:

./write

The first line compiles your code and create an executable called write. The second line runs the executable.