0

我有一个 .txt 文件,如下所示:

(0.781860352, -11.6927013, 7.20992613)  
(0.364501476, -9.41256046, 6.87873077)  
(0.394773483, -7.85253429, 6.90275288)

我需要一个代码来分别从每一行访问每个双精度。我在解决这个问题时遇到了麻烦。有任何想法吗?

谢谢!

更新:

所以,就像我说的,我使用 Kerrek SB 的建议从每一行访问每个双精度数,然后我将这些值存储到向量的组件中,然后我访问每个组件并执行一个操作(比如将它们相乘),并且将结果存储到数组中;最后我添加了数组的内容。无论如何,这是代码:

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;

}

代码有效(实际上它没有正确添加数组的内容),但看起来有点粗糙。我觉得它可以被简化和/或更简洁。有任何想法吗?

4

1 回答 1

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";
}
于 2013-01-15T22:36:28.733 回答