-
File Help
Hello
Why isn't this code working:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
#include <iostream.h>
#include <time.h>
int main()
{
srand((unsigned)time(NULL));
int x=rand()%9;
ofstream value("xvalue.txt", ios::ate, filebuf::sh_write );
if(!value.is_open())
{
cout<<"Could not open file... Error.... Quitting\n";
system("PAUSE");
return 0;
}
value<<"x="<<x<<"; ";
value.close();
char yes;
cout<<"Would you like to view contents of file (up to 200 characters in)?\n y for yes, anything else for quit\n";
cin>>yes;
if (yes=='y' || 'Y')
{
char text[200];
ifstream value_read("xvalue.txt", ios::out | ios::nocreate, filebuf::sh_write);
if(!value_read.is_open())
{
cout<<"error, could not open file\n";
system("PAUSE");
return 0;
}
value_read.getline(text, 200, '\n');
cout<<text[200]; \\this isn't working
system("PAUSE");
value_read.close();
}
return 0;
}
The not working part is it doesn't output the files contents to the screen. And yes, I know there are contents in the file.
-
That was me, wasn't logged in. Where you see the smiley face, it should be ios:: out. forget the space, i had to get that in so you could see what it was.
-
I guess I wasn't logged in again. THat was me.
-
ifstream value_read("xvalue.txt", ios::out | ios::nocreate, filebuf::sh_write);
If you are using ifstream which is used for input, why do you use ios::out which means output to the file. Try removing that. Also, what is filebug::sh_write? I have never seen that before. If you want to open the file for input and output use an fstream instance and give it ios::out and ios::in properties.
-
It's probably working, just not giving you the output you expect.
cout<<text[200]; \\this isn't working
your code will output the the contents of text[200] (which, by the
way, is out of bounds) but not the array's contents. You need to
loop through the array, input-counter-number-of-times.
hth,
-
Just tried that but my compiler (VC++ .NET) says that getline is not a member of fstream. Then it says bianry '<<': ifstream does not define this.
-
I'll give this a shot...
will try to print the 200th element of array text. Try just
Seems too easy...i might be wrong. try it anyway
-
Perhaps if I hadn't already tried that. Does anyone want to take the time out of their day to write a program that works to the same effect (give x a random value, write that to a file, display values in file)?