Home > Back-end >  Reading Floats from a txt file in C
Reading Floats from a txt file in C

Time:01-27

I am trying to read (x,y) floating point values from a txt file in C . The numbers are seperated by a space. In the file, The ith number and the i 1st number make the (x,y) coordinates. So index positions 0 and 1 would be one (x,y) pair and index positions (1,2) would be another (x,y) pair.

This is what I have done but I am not sure how I can save them as floats.

 ifstream randomFile;
        string content;
        randomFile.open("random.txt");
        if(randomFile.is_open()) {
            while(getline(randomFile,content)){
            randomFile >> content;
            }
            randomFile.close();
        }

CodePudding user response:

Read the first float x
While additional read y succeeds:
  Add (x, y) to your list
  x = y

#include <iostream>
#include <vector>

struct xy
{
  float x, y;
  xy( float x, float y ) : x{x}, y{y} { }
};

auto read_xy_pairs( std::istream & ins )
{
  std::vector<xy> xys;
  float x, y;
  ins >> x;
  while (ins >> y)
  {
    xys.emplace_back( x, y );
    x = y;
  }
  return xys;
}

#include <sstream>
#include <string>

int main()
{
  std::cout << "list of numbers? ";
  std::string s;
  getline( std::cin, s );
  std::istringstream numbers( s );
  
  for (auto [x, y] : read_xy_pairs( numbers )) 
    std::cout << "(" << x << ", " << y << ")\n";
}

Example:

list of numbers? 1 2 3 4 5
(1, 2)
(2, 3)
(3, 4)
(4, 5)

CodePudding user response:

An extra variable (prev) can be used to store the value of last input and append (prev,curr) on every iteration to the storage container. In the following code, I have used vector of pairs of float to store the pairs, but you may use arrays or structures as well.

#include<fstream>
#include<iostream>
#include<vector>
using namespace std;

int main() {
    //Declaring vector of float pairs
    vector <pair<float, float>> floatPairs;
    ifstream randomFile;
    float curr, prev;

    randomFile.open("a.txt");
    randomFile >> curr;
    while (!randomFile.eof()) {
        prev = curr;
        randomFile >> curr;

        //Appending to vector of float pairs
        floatPairs.push_back({ prev,curr });
    }

    //Printing
    for (auto i : floatPairs) {
        cout << "(" << i.first << ", " << i.second << ")\n";
    }
}

Input file content: 12.5 56.8 34.7 75.7 23.4 86.7 34.9 66.8

Output:

(12.5, 56.8)
(56.8, 34.7)
(34.7, 75.7)
(75.7, 23.4)
(23.4, 86.7)
(86.7, 34.9)
(34.9, 66.8)
  • Related