我有一个.txt文件,看起来像:
(0.781860352, -11.6927013, 7.20992613)
(0.364501476, -9.41256046, 6.87873077)
(0.394773483, -7.85253429, 6.90275288)
我需要一个代码来分别从每一行访问每个double。我遇到了解决这个问题的麻烦。有什么想法吗?
谢谢!
更新:
所以,就像我说的那样,我使用Kerrek SB的建议从每一行访问每个double,然后我将这些值存储到vector的组件中,然后我访问每个组件并执行一个操作(比如将它们相乘) ),并将结果存储到数组中;最后我添加了数组的内容。 无论如何,这是代码:
int main() {
//=============================
//Initial Declarations
//=============================
Vector3 r(0,0,0);
int num = 0 , i;
string line;
char c, d1, d2, d3, d4;
double v1, v2, v3 , b[num];
//=============================
//Counting Lines in File
//=============================
ifstream is;
is.open ("data.txt");
while (is.good())
{
c = is.get();
if (c=='\n')num++;
}
is.close();
cout<<"Number of lines in file is "<<num<<endl;
//=============================
//Getting Data
//=============================
ifstream infile("data.txt");
for (line ,i=0 ; getline(infile, line), i<=num-1;i++ )
{
istringstream iss(line);
if (!((iss >> d1 >> v1 >> d2 >> v2 >> d3 >> v3 >> d4 >> ws) &&
iss.get() == EOF &&
d1 == '(' && d2 == ',' && d3 == ',' && d4 == ')'))
{
}
// Placing data in vector
r[0] = v1;
r[1] = v2;
r[2] = v3;
//Placing data from vector into array
b[i] = r[0]*r[1]*r[2];
}
// Adding contents of array
valarray <double> bfinal (b,num);
double b_final = bfinal.sum();
cout<< b[0] << "," << b[1] << ", " << b_final << endl;
return 0;
}
代码有效(实际上它没有正确添加数组的内容),但它看起来有点粗糙。我觉得它可以简化和/或更简洁。有什么想法吗?
答案 0 :(得分:9)
标准C ++习语:
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
std::ifstream infile("data.txt");
for (std::string line; std::getline(infile, line); )
{
char d1, d2, d3, d4;
double v1, v2, v3;
std::istringstream iss(line);
if (!((iss >> d1 >> v1 >> d2 >> v2 >> d3 >> v3 >> d4 >> std::ws) &&
iss.get() == EOF &&
d1 == '(' && d2 == ',' && d3 == ',' && d4 == ')'))
{
// error parsing "line"
std::cerr << "Sorry, could not parse '" << line << "'. Skipping.\n";
continue;
}
std::cout << "You said: " << v1 << ", " << v2 << ", and " << v3 << "\n";
}