c++中读取文件中整数串 保存到数组

来源:百度知道 编辑:UC知道 时间:2024/06/23 07:42:33
文件有两行: 第一行仅一个数字;第二行是一串数字

如:

2

1 6 4 3 2 5

现在我需要将 第一行中数字保存到一个变量中

第二行数字串保存到一个数组中

需要使用c++

提前感谢
第二行的数字串是用空格隔开的

文件只有两行

那就太方便了
#include <stdio.h>
int main()
{
int val; //保存变量
int temp;
int a[10]; //我随便用个小数组存储的,你可以自己设计
int i=0,count=0; //count记录数组的长度
FILE *p;
p=fopen("test","r"); //读取文件
fscanf(p,"%d\n",&val); //先读第一行的变量
printf("%d\n",val);
while(fscanf(p,"%d ",&temp)!=-1) //用while循环读取,添加到数组
{
a[i]=temp;
i++;
count++;
}
for(i=0;i<count;i++)
printf("%d ",a[i]); //输出看看对不对
}
/* test 文件
12
10 11 12 13 14 15 16
*/

#include<iostream>
#include<fstream>
using namespace std;

void main()
{
int i=0,k=0;
int number,array[50]={0}; /*数组长度自己选择*/

const char *file="data.txt"; /*读取数据文件的路径名*/

ifstream fin;
fin.open(file);
fin>>number;
cout<<"number:"<<number<<endl; /*输出