I apologize in advance for lack of grammer and or spelling..
I've been programming my own console games for quite sometime and recently have been trying find ways to save player data and hi scores. In my quest i've hit road block after road block. C++ streams just don't seem logical to me! I have several questions which I am really hoping somebody can help me out with.
OK lets says I have a text file called test.dat, and it has "hello world" saved in it. Regardless of binary or text mode, if I do a infile.get(dummy) loop and print the information to the screen, the last character is always echoed!!
For example.
ifstream infile("test.dat");
char dummy;
while(!infile.eof()) // why are there problems!!!!!!
{
infile.get(dummy);
cout << dummy;
}
cout << endl;
This would print out "Hello Worldd"; Now this is extremely annoying, and i'm not sure why it does this.
Ok my 2nd question. This involves testing to see if a file exists, and if it doesn't, then creating the file, write some random garbage, and then attempt to use the input stream on the file again. The problem is the input stream just wont work! If I have this code.
ifstream infile;
ofstream outfile;
char dummy;
infile.open("test2.dat"); // This file doesn't exist
// test to see if file exists.
if (!infile)
{
infile.close();
outfile.open("test2.dat");
outfile << "Hello";
outfile.close();
}
// we know it exists now!
infile.open("test2.dat");
for (int i=0; i<5; i++)
{
infile.get(dummy); // its taking in weird crap, it doesn't print the string at all! Binary, or ascii, its not right.
cout << dummy;
}
cout << endl;
This will print some random garbage, not "Hello".
My third question is about streams being used in functions. A function here takes in a
outfile stream as a parameter. When it writes, it creates the document but doesn't save any
of the text. Why is this?
int WriteSomething(ofstream outfile)
{
//ofstream outfile;
outfile.open("test3.dat");
outfile << "I Know your not gonna save what I write.";
outfile.close();
return 1;
}
int main()
{
ofstream outfile;
WriteSomething(outfile);
return 0;
}[
I know how to solve all of the problems, but that doesn't mean I know why these solutions or problems exist. To solve #1, I use ifstream test stream. (ifstream test("test.data); if(!test){}) I haven't been able to solve #2. In question #3 I solve it by referencing the stream, but that still doesn't tell me why it originally didn't work. Thank you so much for anybodies help.
[edited by - abomb2004 on November 26, 2003 8:04:44 PM]