繁体   English   中英

从 C++ 中的 txt 文件读取浮点数

[英]Reading Floats from a txt file in C++

我正在尝试从 C++ 中的 txt 文件中读取(x,y)浮点值。数字之间用空格分隔。 i个数字和第i+1个数字构成(x,y)坐标。 因此索引位置01将是第一个(x,y)对,索引位置(1,2)将是下一个(x,y)对。

这就是我所做的,但我不确定如何将它们保存为花车。

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

读取第一个浮点数 x
当附加读取 y 成功时:
将 (x, y) 添加到您的列表
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";
}

例子:

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

一个额外的变量 ( prev ) 可用于存储每次迭代时最后输入的值和 append ( prev , curr ) 到存储容器。 在下面的代码中,我使用了浮点对的向量来存储对,但您也可以使用 arrays 或结构。

#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";
    }
}

输入文件内容: 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM