C++逐行读取txt中的数据,并保存到数组中
123
456
789
...
要将数据读取到数组int a[100]中
a[0]=123,
a[1]=456,
a[2]=789依此类推;
求解答。。。C++ 展开
///代码在Dev-C++ 4.9.9.2环境下编译成功!
///new.txt为当前目录下的文件,格式如你所说.
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in("number.txt");
if(not in)
return EXIT_FAILURE;
int a[100] = {0};
int index(0);
int x(0);
while(in >> x)
{
if(index > 99)
{
std::cout << "The array is full of number!\n";
break;
}
a[index] = x;
++index;
}
std::cout << "There are " << index << " numbers in the array!\n";
///print the array
if(not (index == 0))
for(int i=0;i<index;++i)
std::cout << "a[" << i << "] = " << a[i] << "\n";
system("pause");
return 0;
}
int a[100];
fp = fopen("file.txt", "r");
while (1 == fscanf(fp, "%d", &a[num_count] ) )
num_count++;
fclose(fp);
#include <fstream>
#include<iostream>
using namespace std;
void main()
{
fstream file;
file.open("s.txt",ios::in);
if(!file)
cout<<"file not founded"<<endl;
int a [100];
int pos = 0;
while(!file.eof())//是否到文件结尾
{
file>>a[pos];
pos++;
if(pos>=100)
break;
}
file.close();
for(int i = 0;i<pos;i++)
cout<<a[i]<<endl;
}