如何用c++从文件读取数据存入数组?

例如,文本文件里存有"1111100000"十个字符,如何把它每位分开成整形数读入并分别存进数组a[10]的每个元素中?

使用for循环加文件操作函数即可读取txt文件当中的数组。

1、C语言标准库提供了一系列文件操作函数。文件操作函数一般以f+单
词的形式来命名(f是file的简写),其声明位于stdio.h头文件当中。例如:fopen、fclose函数用于文件打开与关闭;fscanf、
fgets函数用于文件读取;fprintf、fputs函数用于文件写入;ftell、fseek函数用于文件操作位置的获取与设置。一般的C语言教程
都有文件操作一章,可以找本教材进一步学习。
2、例程:

#include<stdio.h>
int i,a[100];
int main(){
    FILE * fp1 = fopen("input.txt", "r");//打开输入文件
    FILE * fp2 = fopen("output.txt", "w");//打开输出文件
    if (fp1==NULL || fp2==NULL) {//若打开文件失败则退出
        puts("不能打开文件!");
        rturn 0;
    }
    for(i=0;fscanf(fp1,"%d",a+i)!=EOF;i++);//从输入文件连续读取整数到数组a
    for(;i--;)fscanf(fp2,"%d ",a[i]);//把数组a逆序写入到输出文件当中
    fclose(fp1);//关闭输入文件
    fclose(fp2);//关闭输出文件,相当于保存
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-10-25
#include<iostream>
#include<fstream>
using namespace std;
int main()
{char c[11];
int a[10],i;

ifstream file("123.txt");
file.getline(c,11);

for( i=0;i<=9;i++)
a[i]=c[i]-48;

for( i=0;i<=9;i++)
cout<<a[i]<<" ";

cout<<endl;
file.close();
return 0;

}
//自己定义一个文件123.txt本回答被提问者采纳
第2个回答  2020-05-27
//用我这个就行了
#include
<fstream>
#include
<iostream>
#include
<string>
using
namespace
std;
void
main()
{
fstream
file1;
file1.open("123.txt",ios::in|ios::out|ios::trunc);
//标志位不加trunc的话,文件不存在就没办法创建
if(!file1.is_open())
{
cout<<"file
not
open"<<endl;
return;
}
file1<<"hello!"<<endl<<"ok";
string
str;
//不是mfc程序就不要用mfc里面的类了
file1.seekp(ios::beg);
//不把文件指针定到文件头你是不会读到东西的,因为刚才往文件里写东西已经把文件指针指到文件末尾了
file1>>str;
cout<<str;
}
第3个回答  2019-12-07
#include
#include
#include
using
namespace
std;
int
main()
{
string
name,number;//存储姓名和学号的临时变量
ifstream
in("luo.txt");
if(in)
{
while(!in.eof())
{
in>>name>>number;
//此时姓名和学号已经读取到了name和number中
cout<
评论
0
0
加载更多
相似回答