如何将文件解析为结构向量

时间:2019-03-15 04:03:59

标签: c++ parsing vector struct

我有一个文件,其数据格式如下:

a 1.000 -1.000 1.000

b 7.89 4.56 2.46

c 50 20 10

我开始编写一些代码来分析文件并将数据存储在结构向量中,但是我不确定如何完成此操作。

struct Coordinates
{
    double x;
    double y;
    double z;
}

vector<Coordinates> aVec; 
vector<Coordinates> bVec;  
vector<Coordinates> cVec;  

ifstream exampleFile;
exampleFile.open("example.txt");

// parse file
while(getline(exampleFile, str))
{
    if(str[0] == "a")
    {
        Coordinates temp;
        temp.x = firstNum; // this is where I'm stuck
        temp.y = secondNum;
        temp.z = thirdNum;
        vertVec.push_back(temp);
    }
    if(str[0] == "b")
    {
        Coordinates temp;
        temp.x = firstNum;
        temp.y = secondNum;
        temp.z = thirdNum;
        vertVec.push_back(temp);
    }
    if(str[0] == "c")
    {
        Coordinates temp;
        temp.x = firstNum;
        temp.y = secondNum;
        temp.z = thirdNum;
        vertVec.push_back(temp);
    }
}

2 个答案:

答案 0 :(得分:1)

首先请注意,文件表示为流。
流只是您可以读取的内容。因此,您需要为结构编写流运算符,以便可以读取它们。

git add

它们都继承自git status。因此,当传递给使用流的函数时,它们的行为相同。

git fetch origin master # this will download all commits from remote to local
# then the local branch "origin/master" will have the information of remote's master branch
git merge origin/master # this will merge "origin/master" to local master
# then the local repository is successfully "recovered"
# you can do a git status to see if they are already clean

首先编写结构,以便它知道如何从流中读取自身。

 std::ifstream    file("Data");   // This represents a file as a stream
 std::cin                         // This is a stream object that represents
                                  // standard input (usually the keyboard)

现在编写一些代码来读取坐标类型的对象。

std::istream

答案 1 :(得分:0)

代替使用

if(str[0] == "a")
{
    Coordinates temp;
    temp.x = firstNum; // this is where I'm stuck
    temp.y = secondNum;
    temp.z = thirdNum;
    vertVec.push_back(temp);
}

使用以下内容:

// Construct a istringstream from the line and extract the data from it

std::istringstream istr(str);
char token;
Coordinates temp;

if ( istr >> token >> temp.x >> temp.y >> temp.z )
{
   // Use the data only if the extractions successful.
   if ( token == 'a' ) // Please note that it's not "a"
   {
      // Do the right thing for a
   }

   // Add other clauses.

}
else
{
   // Deal with the error.
}
相关问题