C++,从 txt 读取到矢量的双倍,读取整个文件时出现问题

C++, reading doubles from txt into vector, problems with reading the whole file

本文关键字:读取 文件 问题 txt C++      更新时间:2023-10-16

我有一个文本文件,其中包含 2 列双精度,中间有一个制表符,并尝试将它们读取为 2 个向量。我的第一个问题是它不会遍历整个文件,而是从最后三分之一开始。我的第二个问题是,虽然它确实push_back但它会转换其他一些数字中的数字。我只是无法理解它。

如果我尝试将它们全部放入一个字符串向量中,它可以毫无问题地工作,但我需要它们作为双精度或 int 进行进一步处理

ifstream myfile("TextFile",ios::in);
if (!myfile) 
{
    cout << "Can't open" << endl;
    system("pause");
    return -1;
}

vector<long double> Datenx;
vector<long double> Dateny;
vector<string>lel;
string line;
while (getline(myfile, line)) {
    //  lel.push_back(line);
    string numberx = line.substr(0, 12);
    int pos = line.find("   ");
    string numbery = line.substr(pos + 1, 12);
    stringstream iss(numberx);
    long double x = 0.0;
    iss>> setprecision(10)>>fixed >>showpoint >> x;
    //cout <<fixed<< numberx << endl;
    //cout<<setprecision(10)<<fixed<< x << endl;
    Datenx.push_back(x);
    stringstream is(numbery);
    long double y = 0.0;
    is >> y;
    Dateny.push_back(y);
}
for (int n = 0; n < 100; n++) {
    cout << Datenx[n] << ' ' << endl;
}
    //  cout << fixed << Datenx[2] << ' ' << endl;
    cin.get();
    return 0;

输入文件的一部分:

0.0000000000    0.0006536954
0.0000000100    0.0005515555
0.0000000200    0.0005004856
0.0000000300    0.0001327819
0.0000000400    0.0006945514
0.0000000500    0.0007864773
0.0000000600    0.0001327819
0.0000000700    0.0007354074

输出: 日期向量:

0
1e-08
2e-08
3e-08

输出: 日期向量:

0.000653695
0.000551555
0.000500486
0.000132782

所以Dateny有点正确..它削减了最后一个数字

并且Datenx向量是完全错误的。

先尽量保持简单。如果有效,您可以添加功能。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
  std::vector<double> v1, v2;
  std::string line;
  std::ifstream myFile("input.txt");
  while(getline(myFile, line))
  {
    std::istringstream lineStream(line);
    double first, second;
    lineStream >> first >> second;
    v1.push_back(first);
    v2.push_back(second);
  }
}

我尝试了这个,使用以下"输入.txt"

1.1    1.2
2.1    2.2
3.1    3.2
4.1    4.2
5.1    5.2