[英]c++ How to parse a file into vector of structs
我有一個數據格式如下的文件:
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);
}
}
首先請注意,文件表示為流。
流只是您可以讀取的內容。 因此,您需要為結構編寫流運算符,以便可以讀取它們。
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
。 因此,當傳遞給使用流的函數時,它們的行為相同。
int value;
std::cin >> value; // The >> operator reads from a stream into a value.
首先編寫結構,使其知道如何從流中讀取自身。
struct Coordinates
{
double x;
double y;
double z;
// This is an input function that knows how to read 3
// numbers from the input stream into the object.
friend std::istream& operator>>(std::istream& str, Coordinates& data)
{
return str >> data.x >> data.y >> data.z;
}
}
現在,編寫一些代碼來讀取Coordinate類型的對象。
int main()
{
// Even if you only have a/b/c using a map to represent these
// values is better than having three different vectors
// as you can programmatically refer to the different vectors
std::map<char, std::vector<Coordinates>> allVectors;
char type;
Coordinates value;
// Read from the stream in a loop.
// Read the type (a/b/c)
// Read a value (type Coordinates)
while(std::cin >> type >> value)
{
// If both reads worked then
// select the vector you want and add the value to it.
allVectors[type].push_back(value);
}
}
而不是使用
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.