直接上代码
#include <iostream>
#include <fstream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
//读取输出txt文件
void txtout()
{
cout << "==============================" << endl;
cout << "成功读取txt文件。" << endl;
//创建二维数组分别存储int及string数据
string str[25][4];//用来存放字符串数据
int num[25][2] = { 0 };//用来存放整形数据
ifstream myfile("data.txt");
ofstream outfile("out.txt", ios::trunc);
if (!myfile.is_open()){
cout << "can not open this file" << endl;
}
//遍历读取数据
for (int i = 0; i < 25; i++){
int count = 2;
for (int j = 0; j < 6; j++){
if (j < 2){
myfile >> num[i][j];
}
else{
myfile >> str[i][j - count];
}
}
}
//输出加载的数据
for (int i = 0; i < 25; i++){
cout << num[i][0] << " " << num[i][1] << " "
<< str[i][0] << " " << str[i][1] << " "
<< str[i][2] << " " << str[i][3] << endl;
};
//将数据写入out.txt文件中
for (int i = 0; i < 25; i++){
outfile << num[i][0] << "\t" << num[i][1] << "\t"<< str[i][0] << "\t" << str[i][1] << "\t"<< str[i][2] << "\t" << str[i][3] << endl;
};
myfile.close();
outfile.close();
}
//读取输出csv文件
void csvout()
{
cout << endl;
cout << "=========================================" << endl;
cout << "成功读取csv文件。" << endl;
int a[10][5];//存放数据的二维数组
FILE* file;
if ((file = fopen("test.csv", "r")) == NULL) {
printf("Can't open the file!\n");
exit(0);
}
fseek(file, 3L, SEEK_SET); // 从文件第二行开始读取
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++){
fscanf_s(file, "%d", &a[i][j]);
fseek(file, 1L, SEEK_CUR); /*fp指针从当前位置向后移动*/
}
}
for (int i = 0; i < 10; i++) {
cout << a[i][1] <<"\t"<< a[i][2]<<"\t" << a[i][3] << "\t" << a[i][4] << "\t" << a[i][5] << "\t" << endl;
}
cout << "=========================================" << endl;
}
int main()
{
txtout();
csvout();
system("pause");
return 0;
}
原始数据格式
未完待续
编程小白,望各位大佬批评指正。