I've made a function that receives a line and a delimiter, separates the line and returns a vector of floats (like the split
function in java). This is the function:
vector<float> extractNumbers(string line, char delimiter) {
vector<float> a;
float f;
string forNow = "";
for (unsigned int i = 0; i < line.size(); i++) {
if (line.at(i) == delimeter) {
f = ::atof(forNow.c_str());
cout << ::atof(forNow.c_str()) << endl;
a.push_back(f);
forNow = "";
} else {
forNow += line.at(i);
}
}
f = ::atof(forNow.c_str());
cout << f << endl;
a.push_back(f);
return a;
}
This is the text file I'm trying it with:
3 3
1 1 1
1 2 1
1 1 1
I call this function: vector<float> floatLine = extractNumbers(line, ' ');
When I try to print forNow
parameter I receive the numbers just like in the text, but when I print f
or ::atof(forNow.c_str())
I receive a 0 instead of the first 3 in the first line. Any thoughts?
Just if you don't know about such convenient way of interaction with files. You can use them like this:
float a, b;
float c, d, e;
float f, g, h;
fstream file("data.dat", ios::in);
if (file) {
file >> a >> b;
file >> c >> d >> e;
file >> f >> g >> h;
file.close();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.