Hello, tell me how you can read the database stored in a .txt file and having a similar format:

Val 1 0 1.209279

The file contains about 1500 rows and 4 columns (the name of the value, the X coordinate, the Y coordinate and the value), how can we read the last column and write it into an array?

  • Well, it's elementary to read each line entirely and break it down by a space ... - ampawd
  • Why read the entire "database" ?? from the point of view of resource use, it is not rational, you can make a buffer with the necessary fields of finite length and subtract the required data size from a certain position. then the speed will be higher. - Alex.B

2 answers 2

#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <fstream> #include <string> //Линия в файле. Стоит дать полям боле осмысленные имена, но для примера сойдет struct Line{ std::string first; int second; int third; double fourth; }; //Оператор чтения линии из файла std::istream& operator>>(std::istream &is, Line &line){ is >> line.first; is >> line.second; is >> line.third; is >> line.fourth; return is; } //Функциональный объект, для того чтобы можно было вынуть из Line последнее значние struct LineFourth{ inline double operator()(const Line &line) const{ return line.fourth; } }; int main(int, char*) { std::vector<double> values; std::ifstream file("data.txt", std::ifstream::in); if(!file){ //Не удалось открыть файл return 1; } std::istream_iterator<Line> begin(file); std::istream_iterator<Line> end; //Чтение файла построчно. В values будет помещен последний столбец std::transform(begin, end, std::back_inserter(values), LineFourth()); //Дальше можно что-то делать с values return 0; } 
  • but it can be easier to put the structure in the vector and not to steam with the functions for pulling. - Alex.B
  • @ Akuma925, well, yes, it's even simpler to std::copy(begin, end, std::back_inserter(values); But the person just wanted the last column as an array. - yrHeTaTeJlb
  • Well, duck does not interfere, then from the vector to raise all the values ​​of this field and push them into the array is one cycle - Alex.B
  • @ Akuma925, I see no reason to do the task in two steps, if possible in one. Now, if he will need other fields later, then it is another matter. - yrHeTaTeJlb

You scroll through the lines ... I read the line, I found a space - this is the 1st value, the next space - the 2nd value, etc. to the end of the line