Advertisement

How to do a thing in C++

Started by March 27, 2000 10:39 AM
4 comments, last by MindWipe 24 years, 7 months ago
I''m used to program in Qbasic and VB, and I''ve just started with C++. And now I wonder how to do a thing in C++ In VB you do like this: open filename for output as #1 for i=i to 200 for i2=i to 200 write #1, map(i,i2) next i2 next i close #1 and how do I: open filename for input as #1 input #1, map(i,i2) Can anyone help me? I''m thankful for any help.
"To some its a six-pack, to me it's a support group."
In C++, you use streams to do file I/O like that. To write things to a file, try the following snippet:

#include <iostream>  // This gives you streams#include <fstream>   // This gives you FILE streams...ofstream outfile;  // ofstream == Output File STREAMoutfile.open("filename");for (int i = 0; i < 200; ++i)  outfile << i << endl;outfile.close();---Basically, the file streams can be used just like cin/cout (there is also ifstream, which is an input file stream, and works like cin). Hope this helps...-Brian    
Advertisement
D''oh. That was me. Didn''t get my password in. Sorry. Anyway, if you''ve got any more questions, fire away.

-Brian
For input? Easy.

#include stdio.h // use the greater than/less than symbols around this

char Buffer[80]; // for reading text

void main()
{
FILE *File1 = fopen("myfile.txt", "r"); // the "r" is for read. your compiler should have a whole huge list of the other ones

while (fgets(Buffer, sizeof(Buffer) - 1, File1))
printf("%s", Buffer); // or you can use cout with iostream.h

--------------------


You are not a real programmer until you end all your sentences with semicolons;
www.trak.to/rdp

Yanroy@usa.com

for i=i to 200
for i2=i to 200
write #1, map(i,i2)
next i2
next i
------------- - - --- -
ofstream outfile;
outfile.open("c:\\blahfolder\\blahfile.file");
int i;
for ( i = i; i <= 200; i++)
for ( i2 = i; i <= 200; i2++)
outfile << i << i2;

outfile.close()
Even easier than using fopen and fgets, you can use the standard file stream.

Just include fstream.h and iomanip.h.

Then declare an input stream like...

ifstream inputfile;

Open your file like...

inputfile.open( filepath );

Then you can input one of two ways..

inputfile >> variable;

That method inputs a single variable...if your first line in the file is text, it will input up to the space (if variable is an array of characters.) If variable is an integer or something, it will grab the first number and convert (if needed).

The second method is for getting an entire line...you need to use the getline() function (that's what iomanip.h is for.)

getline(inputfile, variable);


All of this code may not be completely correct, this is just off the top of my head. Hope it helps.


*Tony Chamblee*

Nucleus Software

Edited by - Tony Chamblee on 4/2/00 9:01:45 PM
*Tony Chamblee*
Liquid Flame Software

This topic is closed to new replies.

Advertisement