C++文件读取中,怎样从文件中读取一种类型的数据

1 2 3 4
3 4 5 6
1.22 2.22 3.33 4.11·

怎样只把int型数据读出?
只把int型数据读到一个int型的数组里

使用文件操作函数fscanf读取某一种数据。

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

#include<stdio.h>
int a;
char b,c[100];
int main(){
    FILE * fp1 = fopen("input.txt", "r");//打开输入文件
    FILE * fp2 = fopen("output.txt", "w");//打开输出文件
    if (fp1==NULL || fp2==NULL) {//若打开文件失败则退出
        puts("不能打开文件!");
        return 0;
    }
    fscanf(fp1,"%d",&a);//从输入文件读取一个整数
    b=fgetc(fp1);//从输入文件读取一个字符
    fgets(c,100,fp1);//从输入文件读取一行字符串
    
    printf("%ld",ftell(fp1));//输出fp1指针当前位置相对于文件首的偏移字节数
    
    fputs(c,fp2);//向输出文件写入一行字符串
    fputc(b,fp2);//向输出文件写入一个字符
    fprintf(fp2,"%d",a);//向输出文件写入一个整数
    
    fclose(fp1);//关闭输入文件
    fclose(fp2);//关闭输出文件,相当于保存
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-15
/*
假如要读取文件chengji.txt中的数据。
文件中数据如下:
学生编号 数学 英语
1 80 90
2 66 67
怎样求各学生的平均成绩和总的平均成绩
*/

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

int main()
{
string line;
int head=0,count=0,num;
float math,english,sum_math=0,sum_english=0,average;

ifstream ifs("chengji.txt");
if(!ifs) return -1;

ofstream ofs("chengji_result.txt");
if(!ofs) return -2;

while(getline(ifs,line))
{
istringstream is(line);
if(head==0)
{
//跳过第一行的表头
head=1;
continue;
}
is>>num>>math>>english;
if(count==0)
{
ofs<<"学生编号\t平均成绩"<<endl;
}
ofs<<num<<"\t"<<(math+english)/2<<endl;
sum_math+=math;
sum_english+=english;
count++;
}

if(count>0)
{
ofs<<endl;
ofs<<"数学平均成绩:"<<sum_math/count<<endl;
ofs<<"英语平均成绩:"<<sum_english/count<<endl;
}

ifs.close();
ofs.close();
return 0;
}
第2个回答  2014-03-16

fscanf 函数可以从文件按照你的格式读取文件数据

但是,请必须保证你的文件内容和你所期望读取的数据格式是一致的

 

如果你想从文件读取一个 float 和一个 int,可以像这样子:

float fvar = 0.0f;
int ivar = 0;

// 假设 file 是一个有效的文件指针 ...
fscanf( file, "%f %d", & fvar, & ivar );

本回答被提问者采纳
第3个回答  2014-03-16
我知道 java 怎么弄 c++ 的 cin 有 什么 选择吧
相似回答