C++ 从TXT文件中读取数据存到数组中

比方说一个里面全是整数的TXT文件,整数之间用空格分开,谁能给我一个实现从文件中读取数据到一个自定义数组中的C++代码啊?越快越好

5年前的回答热度还挺高,现添加C++实现的代码:

#include <fstream>

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;


//static const string fileFullPath = "d:\\decimal.txt"; //windows格式输入文件

static const string fileFullPath = "/cy/decimal.txt"; //linux格式输入文件


template<typename T>

void printElement(T& val)

{

    cout << val << endl;

}


template<typename T>

void outputVec(vector<T>& vec)

{

    for_each(vec.begin(), vec.end(), printElement<T>);

}


int main()

{

    fstream fs;

    fs.open(fileFullPath.c_str(), ofstream::in);

    

    vector<int> arrInt;

    while (!fs.eof())

    {

        int a;

        fs >> a;

        arrInt.push_back(a);

    }

    outputVec(arrInt);

    exit(0);

}



===========以下为2016年的原始回答============

#include <stdio.h>

#include <stdlib.h>


#define MAXSIZE 100


main()

{

    FILE *fp;

    if ( (fp = fopen( "c:\\a.txt", "r" )) == NULL ) printf("ERROR!\n");

    int tmp[MAXSIZE];

    int i;

    for ( i=0; i<MAXSIZE; i++ )

    {

        tmp[i] = 0;

    }

    char chtmp[10000];

    i=0;

    while ( !feof(fp) && i!=MAXSIZE )

    {

        fscanf( fp, "%d ", &tmp[i] );

        //printf("tmp[%d]=%d",i,tmp[i]);

        i++;

    }

    for ( i=0; i<MAXSIZE; i++ )

    {

        printf( "tmp[%3d]=%d\n", i, tmp[i] );

    }

    fclose( fp );

    system("PAUSE");

}


TXT文件需要放在c盘根目录

[][][][][]TXT文件内容如下:

1234 5 6 6 6 7 8 8 8356 8 3568 35 8 136 1 8 07 86 89765 7895 765 786 4 654 654 8 790 870 987 0987 87 69 8756 765 87 65 8765 84 3 54 3 458 76 0987 -908 -908 -709 0986 98 76 06 985 7 4 423 6542 6543

温馨提示:答案为网友推荐,仅供参考
相似回答