C/C++ 读取EXCEL数据、字符串

读取数据

#include<iostream>
#include<math.h>
using namespace std;

int a[10];
int main(){
    
    
    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++){
    
    
        fscanf(file, "%d", &a[i]);
        fseek(file, 1L, SEEK_CUR);   /*fp指针从当前位置向后移动*/
    }

    for(int i=0;i<10;i++){
    
    
        cout<<a[i]<<endl;
    }
    return 0;
}

读取字符串
在这里插入图片描述

#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;

const int N=123;
char company[20][20][20];       //读取公司代号
// char temp[200][30];
int main(){
    
    
    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<3;i++){
    
    
        for(int j=0;j<3;j++){
    
    
            fscanf(file,"%[^,\n]",company[i][j]);  // 读到逗号或\n为止
            fgetc(file); // 读取一个字符(逗号或\n)
        }
    }

    for(int i=0;i<3;i++){
    
    
        for(int j=0;j<3;j++){
    
    
            cout<<company[i][j]<<endl;
        }
    }

    return 0;
}

在这里插入图片描述
注意点:
在处理字符串时,fgetc(file); 可以读取一个字符(逗号或\n),会比fseek(file, 1L, SEEK_CUR); 更好用

只读取EXCEL列表的第一列:
在这里插入图片描述

#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;

const int N=12;
char company[200][10];       //读取公司代号
char temp[200][30];
int main(){
    
    
    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=1;i<=N;i++){
    
    
        fscanf(file,"%[^,\n]",company[i]);  // 读到逗号或\n为止
        fgetc(file);
        for(int j=1;j<=2;j++){
    
    
            fscanf(file,"%[^,\n]",temp[j]);
            fgetc(file); // 读取一个字符(逗号或\n)
        }
    }

    for(int i=1;i<=N;i++){
    
    
        cout<<company[i]<<endl;
    }
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44174803/article/details/110739461