C++保存数据到txt并导入excel中绘图(1)

C++运行完成后,有时需要将结果保存在类似txt等的文档中,以便于后续查看或调用。

1、保存到txt文件中

 1 #include <fstream>
 2 
 3 
 4 int main()
 5 {
 6     double Dire_angle = 45 * PI / 180 ;              // 方向角
 7     double center_x = 0.0, center_y = 0.0;           // 第一个航点
 8     double width = 200.0;                            // 宽(直径)
 9     double length = 50.0;                           //
10     double interval = 25;                            // 间隔
11 
12         int N8 = 10;
13     vector<MyPoint>result7 = getserpentine_point(center_x, center_y, Dire_angle, length, width, interval, N8);
14     
15     
16     vector<MyPoint>::iterator start = result7.begin();//指向容器的初始位置
17     vector<MyPoint>::iterator end = result7.end();//指向元素最后一个位置的后一个位置
18 
19     // 向txt文档中写入数据
20     ofstream dataFile;
21     dataFile.open("dataFile.txt", ofstream::app);
22     fstream file("dataFile.txt", ios::out);        // 为输出(写)而打开文件
23 
24     while (start != end)
25     {
26         dataFile<<start->x<<",\t"<<start->y<<endl;       // 写入数据
27         cout << start->x << ", "<< start->y << endl;
28         start++;
29 
30     }
31     dataFile.close();                                    // 关闭文档

上面代码涉及两个知识点:一是vector的遍历方式;二是保存txt文档的方式。

其中,vector的遍历方式选择的是迭代器遍历方式:

 1 #include <vector>
 2 vector<int> v1;
 3 v1.push_back(1);
 4 v1.push_back(2);
 5 v1.push_back(3);
 6 v1.push_back(4);
 7 
 8 //(1)迭代器遍历方式1
 9 vector<int>::iterator start = v1.begin();//指向容器的初始位置
10 vector<int>::iterator end = v1.end();//指向元素最后一个位置的后一个位置
11 while(start != end)
12 {
13     cout << *start << endl;
14     start++;
15 }

vector调用的是stl库,返回的是地址,因此,在使用的时候,要用地址的方式去调用。

 

然后是保存txt文档的方式,这里选择的是使用ofstream:

为了使用它,需要在开头添加一个头文件

1 #include <fstream>

定义打开输出流文件

1    ofstream outfile;//创建文件
2 
3     outfile.open("data.txt");
4 
5     for (i=0;i<10;i++)
6 
7         outfile<<s[i]<<endl;
8 
9     outfile.close();

 打开文件的方式在ios类(所以流式I/O的基类)中定义,有如下几种方式:

ios::in 为输入(读)而打开文件
ios::out 为输出(写)而打开文件
ios::ate 初始位置:文件尾
ios::app 所有输出附加在文件末尾
ios::trunc 如果文件已存在则先删除该文件
ios::binary 二进制方式

 

 

2、导入到excel中

 

(1)打开一份空白的excel表格,按“Ctrl+O”打开之前导出的txt文档

 

(2)选择分割符号,下一步

 

(3)选择逗号,下一步

 

(4)点完成

 

 

 

posted @ 2024-01-22 11:04  taohuaxiaochunfeng  阅读(327)  评论(0)    收藏  举报