从文本文件中读取以填充数组
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
相关文章:
- C++ 填充数组时遇到问题
- 如何使用同时设置计数和填充数组的函数
- 如何使填充数组的函数发送到函数?而不是其参数中的数组
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 使用 memset 填充数组会显示垃圾
- Visual Studio从文件中填充数组时中断
- 分段 填充数组时出错
- 用不同的值填充数组/矢量的边缘和中心
- 使用相同的数据填充数组对象或使用指针
- 是否可以使用三元运算符"?"在 C/C++ 中填充数组列表?
- 填充数组(写入位置0x00000000的访问冲突)
- 从文件中读取输入并填充数组以存储数据供以后使用
- c++当循环在填充数组时没有正确终止时,希望能帮助退出此循环
- 填充数组会导致数组周围的堆栈损坏
- Cuda有效地将数据插入到未排序的填充数组中
- 填充数组的 C++ 函数
- 访问部分填充数组上的第一个打开元素
- 将一个字节数组从C#传递到C++填充数组的C++com对象中
- 如何使用向量中的信息填充数组并从数组中选择随机项
- C,填充数组使用dec2bin转换器