我有一个文件,其中包含逐行存储的浮点数。示例:
1.5222
3.2444
4.0005
12.3331
我希望程序逐行读取文件并将此数字作为字符串存储在向量中,然后将其转换为长双精度。我写了这段代码:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <vector>
using namespace std;
int main()
{
int j = 0;
cout.precision(16);
string s, weights;
cout << "You need to enter the filename of the file containing weights." << endl;
cout << "ENTER weights filename: ";
cin >> weights;
cout << endl;
ifstream weightsfile;
weightsfile.open(weights.c_str());
vector <string> weights_s;
vector <long double> weights_ld;
while(weightsfile >> j) // this loop reads weights from file
{
getline (weightsfile, s);
weights_s.push_back(s);
}
for(j = 0; j < weights_s.size(); j++) // this loop converts string data to long doubles and gives the output
{
weights_ld.push_back(strtold(weights_s[j].c_str(), NULL));
cout << weights_s[j] << endl;
cout << weights_ld[j] << endl;
}
weightsfile.close();
return 0;
}
那是什么问题?输出为:
.5222
0.5222
.2444
0.2444
.0005
0.0005
.3331
0.3331
我想我的程序会跳过小数点前的数字。我该怎么做才能解决此问题?
答案 0 :(得分:1)
while(weightsfile >> j)
从每行的开头读取一个整数,您对getline
的调用然后读取该行的其余部分。
while(getline(weightsfile, s))
{
weights_s.push_back(s);
}
会有理想的效果。
您实际上是否需要字符串列表?您能立即转换为双打吗(通过一些额外的错误检查):
while(getline(weightsfile, s))
{
size_t pos;
weights_ld.push_back(std::stold(s, &pos));
if (pos != s.size())
{
throw std::invalid_argument("invalid weight");
}
}