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

比方说一个里面全是整数的TXT文件,整数之间用空格分开,谁能给我一个实现从文件中读取数据到一个自定义数组中的C++代码啊?越快越好... 比方说一个里面全是整数的TXT文件,整数之间用空格分开,谁能给我一个实现从文件中读取数据到一个自定义数组中的C++代码啊?越快越好 展开
 我来答
无大智有大勇
推荐于2016-08-29 · TA获得超过441个赞
知道小有建树答主
回答量:502
采纳率:0%
帮助的人:330万
展开全部

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

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式