2016-02-28 90 views
-2

我想读从每行有3个双打的文本文件3个双打文本文件(行数是不知道事先)。然后将这些双打保存到3个不同的阵列中,以便稍后使用双打。或者一次读取程序1号线,将其保存就行了,用3个双打,我需要再转到下一行使用下一个3个双打。保存双打,以供以后使用C++

哪一种方法是使用/保存这些双打更好?

如果数组是一个更好的方式来保存它们,我该如何创建一个数组来计算文件的行数以知道它应该有多少元素,并在读取文件时将值保存在正确的数组中?

我的文件读取的代码如下所示到目前为止

ifstream theFile("pose.txt"); 
double first,second,third; 
while(theFile >> first >> second >> third){ 
    cout<<first<<" " << second <<" "<< third<<endl; 
    /*some code here to save values in different arrays for 
    use later or use the 3 values straight away while keeping the line 
    number and then moving on to the next line to use those values 
    straight away*/ 
} 

代码或建议,我对这个问题的逻辑欢迎任何帮助,

感谢。

编辑:首先我不知道如果我的值保存到一个数组的逻辑是正确的设计智慧,其次我不知道怎么这三个值在循环中添加到不同的数组。

+2

了什么问题吗...? –

+0

检查编辑我已使问题更清楚。 –

+1

你没有一个数组,你的问题仍然不清楚。查看帮助中心,了解您应该在此处询问哪些问题。 –

回答

0

结构的一些矢量可能有帮助:

struct Values { 
    double first; 
    double second; 
    double third; 
}; 

std::vector<Values> v; 

while(theFile >> first >> second >> third){ 
    cout<<first<<" " << second <<" "<< third<<endl; 
    Values values; 
    values.first = first; 
    values.second = second; 
    values.third = third; 
    v.push_back(values); 
} 

完成相关的行号,你也可以使用地图

std::map<int,Values> m; 
int lineno = 1; 
while(theFile >> first >> second >> third){ 
    cout<<first<<" " << second <<" "<< third<<endl; 
    Values values; 
    values.first = first; 
    values.second = second; 
    values.third = third; 
    v[lineno++] = values; 
} 
+0

如果我使用结构方式,那么我将如何调用第一行的值以供使用,然后第二等? –

+0

你可以简单地用'V [1] .first','V [2] .first'等 –

+0

Euxaristw破虏! –

0

使用stringstreams(#include <sstream>)应该是有帮助的。

// Example program 
#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std; 
int main() 
{ 
    string line; 
    while(getline(cin,line)) 
    { 
     stringstream str(line); //declare a stringstream which is initialized to line 
     double a,b,c; 
     str >> a >> b >> c ; 
     cout << "A is "<< a << " B is "<< b << " C is " << c <<endl; 
    } 
} 
相关问题