从文本文件读取以填充数组
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]
(空格可以省略)。
写作:
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
我的目标是将值存储到文本文件中,然后通过读取文本文件填充数组。
目前,我将值存储到文本文件中;
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]
(空格可以省略)。
写作:
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