-4

I have a file with the following pattern: 0.123,0.432,0.123,ABC

I've successfully retrieved the float numbers to an array, but I need now to find a way to get the last string. My code is the following:

    vector<float> test;
    for (float v = 0; test_ss >> v; ) {
        test.push_back(v);
        test_ss.ignore();
    }

Tips:

  • As the number of elements in each line is known its not a problem
  • Also I don't particularly need to use this structure, I was just using it because it was the best I've found so far.
  • All I want is in the end to have a vector with the float elements and a string with that last field.

2 Answers2

0

A simple solution would be to first replace the string using std::replace( test_ss.begin(), test_ss.end(), ',', ' '); then to use your for loop:

vector<float> test;
for (float v = 0; test_ss >> v; ) {
    test.push_back(v);
    test_ss.ignore();
}
Jake Freeman
  • 1,700
  • 1
  • 8
  • 15
0

RegEx would be an overkill for this task, and substr will return string while you asked for float vector. I think what you need is to use ifstream and read comma into a dummy char:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

int main() 
{
    std::ifstream ifs("file.txt");

    std::vector<float> v(3);
    std::string s;
    char comma; // dummy

    if (ifs >> v[0] >> comma >> v[1] >> comma >> v[2] >> comma >> s)
    {
        for (auto i : v)
            std::cout << i << " -> ";

        std::cout << s << std::endl;
    }

    return 0;
}

Prints:

0.123 -> 0.432 -> 0.123 -> ABC
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37