how to convert char to const char*

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”.


-------------------------------------------------------------------------------

int oldnewcomp_temp(char* lcfile)
{
using namespace std;

int year;
char yeardata;

ifstream inFile2009b;
inFile2009b.open(lcfile);
inFile2009b >> year >> yeardata ;
inFile2009b.close();

......

ifstream yearlydata;
yearlydata.open(yeardata);
......

yearlydata.close();

return 0;
}



You have to use std::string unless you can guarantee the length of yeardata.
L B (5912)
Sorry, I am quite new to C++, could you explain further?

where should I put std::string?
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;
}
Last edited on
Topic archived. No new replies allowed.