C++读取txt

来源:互联网 发布:erdai cms 编辑:程序博客网 时间:2024/05/29 02:23
#include <string>#include <vector>#include <iostream>#include <fstream>using namespace std;void main(){    ifstream fin("2.txt");//读取文件“2.txt”注意,文件须放在工作空间下。读取后产生 流型 文件fin        double a[902],b[451],c[451];        int i;        for(i=0;i<=901;i++)        {                fin>>a[i];//将数据流送入矩阵a        }        for(i=0;i<=901;i=i+2)        {                b[i/2]=a[i];                c[i/2]=a[i+1];        }        for(i=0;i<=501;i=i+2)        {                cout<<a[i]<<" "<<a[i+1]<<" "<<b[i/2]<<" "<<c[i/2];                cout<<endl;        }}

这样就生成了两个数组b,c对应x,y.
然后,在生成txt文件,为了实现这个目的,上网查询的以下代码(头文件为#include <stdio.h>)
FILE *fp;
    fp=fopen("d:\double.txt","w");
        for(i=0;i<=450;i++)
    fprintf(fp,"%6.2lf\n",b[i]);

    fclose(fp);


#include<iostream>#include<fstream>#include<strstream>#include<string>#include<vector>using namespace std;typedef struct{string name;int age;string add;void out(){cout<<"Name:"<<name<<endl<<"Age:"<<age<<endl<<"Add:"<<add<<endl;}}student;int main(){ifstream infile("data.txt",ios::in);vector<int>err;  if(!infile)  {   cerr<<"open error!"<<endl;   exit(1);  }  string s;  int n,i=0,flag=0;  //student st[8];  infile>>n;  student *st=new student[n];  while(n--)  {   //getline(infile,s);   flag=0;   infile>>st[i].name>>st[i].age>>st[i].add;   //infile>>st[i].age;   //infile>>st[i].add;   string::size_type j;   string c;   for(j=0;j<st[i].name.size();j++)    if(!isalpha(st[i].name[j]))    {     flag=1;     break;    }   if(flag==0)   {    if(st[i].age>120||st[i].age<0)     flag=1;   }   if(flag==0)   {    for(j=0;j<st[i].add.size();j++)    if(!isalpha(st[i].add[j]))    {     flag=1;     break;    }   }   if(flag==1)err.push_back(i);   i++;  }     infile.close();  ofstream outfile("err.txt");  if(!outfile)  {   cerr<<"open err.txt error!"<<endl;   exit(1);  }  vector<int>::size_type ei;  for(ei=0;ei<err.size();ei++)   outfile<<st[err[ei]].name<<" "<<st[err[ei]].age<<" "<<st[err[ei]].add<<endl;  outfile.close();  delete [] st;     return 0;} 

data.txt输入文件
-----------------------
8
zhangSan 23 beijing
lisi 123 shanghai
mawu 56 liaoning22
zhao3LIU 12 guangxi
huangqi 30 jiangxi
wangba -32 hu2nan
haijiu 43 yunnan
haoshi 21 xinjiang
------------------------

err.txt输出文件,运行之后会显示如下内容
------------------------
lisi 123 shanghai
mawu 56 liaoning22
zhao3LIU 12 guangxi
wangba -32 hu2nan