-
reading a file
I currently have the lines of code ->
ifstream save1("save1.txt", ios::in); //initializes file
for (int k=0; k<10; k++) {save1>>name1[k];} //Pulls in the code, works fine
for(int i=0;i<10;i++) {if(name1[i]){render_the_name(//PS this works okay)}} //If the file was true then print out its name
My problem is this, the code pulls the name out of the file but I need it later :(
How do I use 'read' or is there another method to read an arary of numbers without affecting them.
PS If it helps the raw code is written like -> 0 12 65 16 32 etc.
-
Code:
ifstream save1("save1.txt", ios::in); //initializes file
for (int k=0; k<10; k++) {save1>>name1[k];} //Pulls in the code, works fine
for(int i=0;i<10;i++) {if(name1[i]){render_the_name(//PS this works okay)}} //If the file was true then print out its name
Try using argc and argv
Code:
#include <iostream.h>
int main( int argc, char *argv[] ) {
.
.
.
ifstream save1 ( argv[1], ios::in );
.
.
The user enters the name of the program, then the file, ie.
C:\>Program textfile.txt
-
Thanks, I'll go and read up on those commands and see if it works :)
-
As I understand it you know that the following data reside in the file named save1.txt.
0 12 65 16 32
and you are saving the data in an array of type int called name1 within your program.
If that is true then you know the name of the file in advance and it can be stored as a string to be used whenever you want.
I am not sure what you mean by "if the file was true". If you mean the file was found and it was able to be opened and there was data in it then you can use if(!save1) to check that file was found and opened successfully. To see if anything was written into name1 I would change the first for loop to a while loop incrementing the index each time through the loop. If the index is greater than what it was intialized at then at least one integer was found in the file.
//declare variables
int name1[10];//array of 10 ints
char filename[] = "save1.txt";//name of file to open
int k = -1;//index variable
//declare ifstream and asssociate it with a file
ifstream save1(filename);
//if unable to find or open file say so
if(!save1)
{
cout << "unable to open file " << filename << endl;
}
while(!save1.eof())//as long as there is data to be read
save1 >> name1[++k];
//if no data in file
if(k == -1)
{
cout << filename << " was empty" << endl;
}
else
{
//print to screen as many data as available, space delimited.
for(i = 0; i <= k; i++)
{
cout << name1[i] << " ";
}
}
-
My apologies to everyone who answered because I actually screwed up the code in another area. Each time I called name1[] I accidently overwrote it in another part of the code :(
The joys of programming :cool: