How do i open a file?
#include <iostream>
#include <fstream> // needed for file functions
using namespace std;
int main()
{
ifstream in("yourFile.txt"); // open file for reading
if(!in.is_open()) // if file is not open - exit
exit(1);
in.close(); // close file
//pause window
cin.ignore();
cin.get();
return 0;
}
simple right?
But how do I read the file?
#include <iostream>
#include <fstream>
#include <string> // used for getline and string
using namespace std;
int main()
{
ifstream in("yourFile.txt");
if(!in.is_open())
exit(1);
string line = ""; // The file will buffer every line into this string
while(getline(in,line)) // loop through the file
{
cout<<line<<endl; // output every line to the screen
}
in.close();
//pause window
cin.ignore();
cin.get();
return 0;
}
Getline will loop through every line in the file and it will store that line temporarly in the string
So now you can read a file right? But what if you want to do data operations that involve actual numbers?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream in("yourFile.txt");
if(!in.is_open())
exit(1);
string line = "";
vector<double>numbers(0); // This vector will be used to store all of the data
while(getline(in,line))
{
numbers.push_back(atoi(line.c_str())); //atoi expects a const char so you must convert
}
// you now have all of the lines stored in the vector as doubles
// lets output the vector
for(int i=0; i<numbers.size(); i++)
cout<<numbers[i]<<endl; // output to screen
in.close();
//pause window
cin.ignore();
cin.get();
return 0;
}
This method works fine if your file is in the following format
Quote
12345
12345
12345
12345
12345
12345
12345
But sometimes our data is stored like this in our file
Quote
12345 12345 12345 12345
12345 12345 12345 12345
12345 12345 12345 12345
well how do we store the individual numbers? ... by tokenizing
example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>// used for istringstream
using namespace std;
// this function takes a string pointer and pushes numbers into a
// vector by tokenizing the string at spaces ' '
void parse(string *ext, vector<int>&types)
{
istringstream iss(*ext);
string token;
// you can replace ' ' with whatever you
// would like to parse at
while(getline(iss,token,' '))
types.push_back(atoi(token.c_str())); // push numbers into vector
}
int main()
{
ifstream in("yourFile.txt");
if(!in.is_open())
exit(1);
string line = "";
vector<int>numbers(0);
while(getline(in,line))
{
// call our function
parse(&line,numbers);
}
for(int i=0; i<numbers.size(); i++)
cout<<numbers[i]<<endl; // output to screen
in.close();
//pause window
cin.ignore();
cin.get();
return 0;
}
I hope this left you with a farther understand of file IO and using IO for numberic data






MultiQuote


|