[英]Reading from a text file to populate an array
我的目標是將值存儲到文本文件中,然后通過讀取文本文件來填充數組。
目前,我將值存儲到文本文件中;
Pentagon.CalculateVertices();//caculates the vertices of a pentagon
ofstream myfile;
myfile.open("vertices.txt");
for (int i = 0; i < 5; i++){
myfile << IntToString(Pentagon.v[i].x) + IntToString(Pentagon.v[i].y) + "\n";
}
myfile.close();
我已將值存儲到此文本文件中,現在我想從創建的文本文件中填充數組;
for (int i = 0; i < 5; i++){
Pentagon.v[i].x = //read from text file
Pentagon.v[i].y = //read from text file
}
這就是我現在所擁有的一切; 誰能告訴我如何實現代碼所說的內容。
您不需要將int
轉換為std::string
或char*
。
myfile << Pentagon.v[i].x << Pentagon.v[i].y << "\n";
// this will add a space between x and y coordinates
閱讀如下:
myfile >> Pentagon.v[i].x >> Pentagon.v[i].y;
<<
和>>
運算符是流的基礎,你怎么沒有遇到它?
您也可以使用自定義格式,例如[x ; y]
[x ; y]
(空格可以省略)。
寫作:
myfile << "[" << Pentagon.v[i].x << ";" << Pentagon.v[i].y << "]\n";
讀:
char left_bracket, separator, right_bracket;
myfile >> left_bracket >> Pentagon.v[i].x >> separator << Pentagon.v[i].y >> right_bracket;
// you can check whether the input has the required formatting
// (simpler for single-character separators)
if(left_bracket != '[' || separator != ';' || right_bracket != ']')
// error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.