n00b c++ code

just learned how to write and retreive files in c++
:cool:


//philip
#include< iostream.h >
#include< fstream.h > //neccesary for writing files

void main()
{
	//variables
	char userName[25];  
	int age;   
	ofstream outfile; 
             
 	cout<<"Enter Your Name: ";
	cin.get(userName, 25);
	cout<<Enter Your Age: ";
	cin>>age;


	outfile.open     

                 ("c:/windows/desktop/NameAge.txt", ios :: out); 

	if(outfile) //check for error
	{
		outfile<<userName<<endl;
		outfile<<age<<endl
			outfile.close();
	}
	else //file not open
	{
		cout<<"A fatal error has occured please curl up and die. 
";
	}
}

edit–> why wont it show al the code?

why do u use:

ofstream outfile;
and then:
outfile.open(“blah[…]”, ios :: out);

i mean, you’ve declared the variable ‘outfile’ as being an ofstream class type, which is a class derived from fstream, specially for writing in a file…

that is where it writes the file to


outfile.open     

                 ("c:/windows/desktop/NameAge.txt", ios :: out); 

the code is to make a new file on the desktop and open it


outfile<<userName<<endl;
        outfile<<age<<endl;

then this command takes the variables that the user entered
and writes them to the open file

outfile.close();

and of course this command closes the open file

oh, and one more thing: if you include the fstream header it’s not neccessary to also include iostream.h, because the fstream header uses the iostream.h, so it will include it automaticly…

know what i mean ? :slight_smile:

shiat, i didnt know that
ill try that out lata
thanks man
save me at least 2 or 3 seconds of typing

in order to be a good programmer, u must know EVERYTHING… so i said u should know that… one thing from me, one thing from somebody else…

and anyway, the thing with iostream and fstream it’s a basic thing… any begginer knows that…

There is no point of not including in iostream.h

All header files should have #ifndef #define so you aren’t including it twice. Not including it in just makes your code more difficult to maniupulate. Say you remove fstream, and use a diffrent header file for file manipulation that dosen’t include iostream?

Its dumb not to include in everything your program relies on.

you are right in a way… but i thought Kaotic should know about this thing… that’s all

and anyway, when you’re writing a program, either you use file manipulation, either you don’t… before you write a piece of code, you make some plans like ‘what is this program going to do and so on’…

anyway (again), it’s no use to talk about #include, i just gave Kaotic some information, his real problem is something else, right?

thanks for the advice homies

heh… no problem… :slight_smile: