C++,从 txt 读取到矢量的双倍,读取整个文件时出现问题
C++, reading doubles from txt into vector, problems with reading the whole file
我有一个文本文件,其中包含 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
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中