第1个回答 2011-12-02
简单的办法:
#include <stdio.h>
...//这里的你自己的程序,省去
FILE *fp = fopen("你的文件的文件名", "r");
int n;
while (!feof(fp))
{
fscanf(fp, "%d", &n);
..//读出的数在n里,一次一个数
}
fclose(fp); //读完就退出循环本回答被提问者采纳
第2个回答 2015-07-31
打开文件 fopen("需要打开的路径")
然后使用fgets函数读取行
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1024
int main()
{
char buf[MAX_LINE]; /*缓冲区*/
FILE *fp; /*文件指针*/
int len; /*行字符个数*/
if((fp = fopen("test.txt","r")) == NULL)
{
perror("fail to read");
exit (1) ;
}
while(fgets(buf,MAX_LINE,fp) != NULL)
{
len = strlen(buf);
buf[len-1] = '\0'; /*去掉换行符*/
printf("%s %d \n",buf,len - 1);
}
return 0;
}
第3个回答 2011-12-02
/*假设你的数据文件是d:\ttt.txt
用循环把数字读到数组a里面顺便显示出来 */
#include <stdio.h>
int main()
{
double a[100];
int i=0;
FILE* fp;
if((fp=fopen("d:\\ttt.txt","r"))==0)
{
printf("无文件!!\n");
return -1;
}
while(!feof(fp))
{
fscanf(fp,"%lf",&a[i]);
printf("%lf\n",a[i]);
i++;
}
fclose(fp);
return 0;
}本回答被网友采纳
第4个回答 2011-12-02
利用输入输出流打开文件,然后按行读取放到string类型,然后再重定向到 double类型中,程序如下已经过调试:
#include <iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
void main(){
fstream in;
in.open("D:\\1.txt",ios::in);
string temp;double data;
while(getline(in,temp))
{
istringstream stream(temp);
stream>>data;
cout<<data<<endl;
}
}
还有更简单的方式,如果一行只有一个单词的话
while(in>>data) {
cout<<data<<endl;
}