I have a file which contains a year and the name of an associated file to be read.
I need to extract the data in the txt file and perform some calculations.
( year data file)
2004 2004data.txt
2005 2005data.txt
2006 2006data.txt
...............................................
Here is what I do. I first declare "char yeardata" and then pass "2004data.txt" to it. Then I call yeardata in ifstream to extract the data inside the file "2004data.txt". The problem is that char yeardata is not constant so I cannot pass the file to it. It doesn't work if I change "char yeardata“ to ”const char yeardata”.
std::string is a type like char, except char only holds one character and std::string holds a string of characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <string> //you need this
#include <fstream>
#include <iostream>
int main()
{
int year;
std::string yeardata;
{
std::ifstream in ("name of file.txt");
in >> year >> yeardata;
//If yeardata has spaces in it, you have to do this:
//std::getline((in >> year), yeardata);
}
std::cout << "Year = " << year << ", Year Data = \"" << yeardata << "\"" << std::endl;
}