-
reading saved file
ok i am making a game and i wont to save it. like with file inout and output so when the program ends it will be able to use the data.
so what i was thinking hay lets have it make a .txt file and have it save the numbers ther.
but how do i get is to read specific lines of the file and output only that here is a kind of example of what i wanna do:
the file says this:
ok that was me example text file now how would i get it to output from that file somehting like this:
or
like that with just and output of one line.
for the numbers i wont to be able to store and assign them.
ps thanx in advance for however can help me.
-
1) attempt to open the file. if file does not exist, handle the error.
2) ok.. file exists. read in the entire file, loading each word into a vector of strings. (if you know for certain your file will be a fixed number of words, feel free to use a static array of strings instead of vector)
3) your file is now in an easily accessable data structure. access your vector just like you would a normal array.
The two most popular methods for reading from a file: use getline( ) in a loop to read in an entire line from the file at a time. -or- use (ifstreamObject >> stringObject) in a loop to read in a single word at a time from the file.
Here is a tutorial on how to use the fstream library for file i/o. Might not be easy to follow for a beginner. Google for basic c++ file i/o if necessary.
Here is an example program using <fstream> and <vector> constructs.. and the getline( ) function. focus on how the files are opened and loaded into the program.
Here is a program that will read in from a file word at a time.
Testing to see if file exists is more important for a read operation than a 'write' operation. If the file does not exist for a write operation, fstream will simply create the file, then write to the file. However, if you are trying to read from a file that does not exist, your program will come to a grinding halt unless you properly handle the error (perhaps prompting the user to re-enter the file name.. or even ask to create a new file.. or whatever, just handle the error)