[英]Reading from a text file to populate an array
The goal I am going for is to store values into a text file, and then populate an array from reading a text file. 我的目标是将值存储到文本文件中,然后通过读取文本文件来填充数组。
At the moment, I store values into a text file; 目前,我将值存储到文本文件中;
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();
I have stored the values into this text file, now I want to populate an array from the text file created; 我已将值存储到此文本文件中,现在我想从创建的文本文件中填充数组;
for (int i = 0; i < 5; i++){
Pentagon.v[i].x = //read from text file
Pentagon.v[i].y = //read from text file
}
this is all I have for now; 这就是我现在所拥有的一切; can someone tell me how you can achieve what the code says.
谁能告诉我如何实现代码所说的内容。
You don't need to convert int
to std::string
nor char*
. 您不需要将
int
转换为std::string
或char*
。
myfile << Pentagon.v[i].x << Pentagon.v[i].y << "\n";
// this will add a space between x and y coordinates
Read like this: 阅读如下:
myfile >> Pentagon.v[i].x >> Pentagon.v[i].y;
<<
and >>
operators are the basics of streams, how come you haven't come across it? <<
和>>
运算符是流的基础,你怎么没有遇到它?
You could also have a custom format, like [x ; y]
您也可以使用自定义格式,例如
[x ; y]
[x ; y]
(spaces can be omitted). [x ; y]
(空格可以省略)。
Writing: 写作:
myfile << "[" << Pentagon.v[i].x << ";" << Pentagon.v[i].y << "]\n";
Reading: 读:
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.