Post by Malagrond on Feb 22, 2011 14:08:46 GMT -6
C++ makes reading text files extremely easy. You only need to include one library to make it work.
First off, add this line to your pre-processor directives (#include, #define, etc.)
Then, to make sure you can use the functions involved, add this line before your function main():
To read from a file, you first have to initialize the file's identifier like so:
Next, tell the newly created ifstream to open a file:
You can also do this in one line with:
Now that you've give the ifstream a file to read, you can start reading from it. However, to avoid errors or unexpected behavior, be sure to wrap your code in an if statement to check that the file opened properly.
You can read data from a file like so:
This will read the first set of data into mystorage. There are two things to note here:
If you wish to read in multiple variables, you can put them all in one line like so:
This will read the first encountered data and store it in str1. It will then skip the next whitespace and read the next set of characters, storing it in str2.
When you are done using your input file, it is good habit to close the file:
That's all there is to it! If you need more help with this, you can try checking out this article for more information.
First off, add this line to your pre-processor directives (#include, #define, etc.)
#include <fstream>
Then, to make sure you can use the functions involved, add this line before your function main():
using std::ifstream;
To read from a file, you first have to initialize the file's identifier like so:
ifstream myfile;
Next, tell the newly created ifstream to open a file:
myfile.open("inputfile.txt");
You can also do this in one line with:
ifstream myfile("inputfile.txt");
Now that you've give the ifstream a file to read, you can start reading from it. However, to avoid errors or unexpected behavior, be sure to wrap your code in an if statement to check that the file opened properly.
if(myfile){
// Instructions
}
You can read data from a file like so:
char mystorage[20];
myfile >> mystorage;
This will read the first set of data into mystorage. There are two things to note here:
- This will read data until a whitespace is encountered. This includes single spaces, tabs, and newlines.
- If the data read is longer than 20 characters, mystorage will only contain the first 20 characters of the input. Be sure to use an appropriately sized variable.
If you wish to read in multiple variables, you can put them all in one line like so:
char str1[20], str2[20];
myfile >> str1 >> str2;
This will read the first encountered data and store it in str1. It will then skip the next whitespace and read the next set of characters, storing it in str2.
When you are done using your input file, it is good habit to close the file:
myfile.close();
That's all there is to it! If you need more help with this, you can try checking out this article for more information.