0

In the main function, there are various vectors of different template types(float, int, char*). This function is called to read in formatted input from different files to fill each vector. My problem is coming from the type conversion since

v.push_back((T)(pChar));

does not like converting char* to float(presumably because of the decimal point).

Question: Is there a way to get correct conversions regardless of the data type as long as the input file is appropriate? (I've considered typeid(); but am not sold on using it)

template <class T>
void get_list(vector <T> & v, const char * path)
{
    fstream file;
    const char delim[1]{' '};
    char line[512];
    char * pChar;

    file.open(path, ios_base::in);
    if (file.is_open())
    {
        while (!file.eof())
        {
            file.getline(line, 512);
            pChar = strtok(line, delim);
            while (pChar != NULL)
            {
                v.push_back(pChar);
                pChar = strtok(NULL, delim);
            }
        }
        file.close();
    }
    else
    {
        cout << "An error has occurred while opening the specified file." << endl;
    }
}

This is homework but this problem does not pertain directly to the objective of the assignment. The assignment is on heaps for data structs/algorithm class.

Sparky
  • 3
  • 2
  • See also e.g. [while eof question / answer](http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line). – Tony Delroy Nov 13 '14 at 08:09
  • There is a [stof](http://en.cppreference.com/w/cpp/string/basic_string/stof) if you are using c++11 compiler. – sop Nov 13 '14 at 08:12

1 Answers1

2

Indeed, you can't simply cast a string to an arbitrary type, you'll need some code to parse and interpret the contents of the string. The I/O library has string streams for that:

std::stringstream ss(pChar);
T value;
ss >> value;
v.push_back(value);

This will work for all types that have a >> overload, including all built-in numeric types like float.

Alternatively, you might want to get rid of the nasty C-style tokenisation:

T value;
while (file >> value) {
    v.push_back(value);
}

or

std::copy(
    std::istream_iterator<T>(file), 
    std::istream_iterator<T>(),
    std::back_inserter(v));

At the very least, change the loop to

while (file.getline(line, 512))

checking the file status after reading the line, so you don't process the final line twice.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644