[英]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.