从文本文件中读取以填充数组

Reading from a text file to populate an array

本文关键字:填充 数组 读取 文本 文件      更新时间:2023-10-16

我的目标是将值存储到文本文件中,然后通过读取文本文件来填充数组。

目前,我将值存储到一个文本文件中;

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::stringchar*

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](可以省略空格)。

写作:

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