zoukankan      html  css  js  c++  java
  • 第三章 实战演习

            文件读写

           通常在比赛中,一道题会有多组测试数据,只有全部测试数据通过,该题才能得满分。那么试想一下,如果在测评时,每道题都是手工输入测试数据再手工检查结果是否正确,那一定是一件让人崩溃的事情。所以比赛要求选手编写的代码必须按要求能自动读取文件中的测试数据,并将运算结果按指定格式以文件格式保存,评测软件如Cena等可以自动比较所有选手的提交答案文件和标准答案文件是否相同而给予相应的分数。这种做法极大地提高了工作效率并且保证了结果的正确性。现以一道简单的比赛仿真题来具体说明。

         【例题描述】     求中间数(mid.  cpp/c/pas)

          对于任意输入的三个整数中,找出大小顺序处于中间的那个数。

         【输入格式】 

          输入文件为mid.in,共一行,即三个整数,以空格相隔。

        【输出格式】

         输出文件为mid.out,共一行,即中间数。

        【输入样例】

          1 2 3

        【输出样例】

          2

        【时间限制】

         1秒

                            这道题表达的是意思如下:

                           对于Pascal选手来说,提交的源程序名为mid. pas,C选手提交的程序名为mid.c,C++选手提交的程序名为mid.cpp。不允许提交可执行文件。

                          源程序编译运行时,读取mid.in文件里的数据,输出结果需写到mid.out文件中。每组测试数据必须一秒钟之内出解。另外要注意的是:一定要严格按格式输出,不允许增减任何字符包括空格,输出的最后一行一般应以换行符结束。

            读写文件主要有以下几种方法,初学者,只要先熟练掌握其中的一两种方法即可。

            方法一(freopen)。

            此方法是利用freopen将输入、输出重定向到文件中。例如下面的程序从sum.in文件中读取两个整数,计算出两整数之和后输出到sum.out文件中。

    //freopen方式读写文件
    //
    #pragma once #include "pch.h" #include <iostream> #include <cstdlib> //此行必加,否则linux下可能出问题 using namespace std; //#define _CRT_SECURE_NO_WARNINGS int main() { int a, b; FILE* infile, *outfile; freopen_s(&infile,"sum.in","r",stdin); //从sum.in中读取数据 freopen_s(&outfile,"sum.out","w",stdout); //输出到sum.out文件 cin >> a >> b; cout << a + b << endl; system("pause"); //一定要将此句注释掉 }

    #include <iostream>
    using namespace std;
    int a,b;
    int main()
    {
      freopen("sum.in","r",stdin);
      freopen("sum.out","w",stdout);
      cin>>a>>b;
      cout<<a+b<<endl;
      return 0;
    }

                 只需加入第11、12(6、7)行语句,即可很方便地实现读写文件数据的功能。源代码及读写文件名需根据题意严格定义。

                          注意:要成功运行该程序,一定要用记事本软件事先建立一个输入文件即文件名为“sum.in”的文件放在该程序的同一文件目录下,否则程序运行时,会因无法找到输入文件而报错。此外,sum.in文件里应该有两个用空格分割的整数用于程序的读取和计算。

                          一定要把system("pause");这句代码去除,否则输出文件中会多输出“请按任意键继续...”这一个字符串而导致评测错误。

                          千万注意文件名别保存为“sum.in.txt”了。

             上例是已知输入文件中的数据个数,如果在不知道文件中有多少个数据的情况下,如何正确读取数据并输出呢?请看下例:

    //读取文件到末尾
    #pragma warning(suppress : 4996)
    #include "pch.h"
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    #define _CRT_SECURE_NO_WARNINGS
    
    int a[5000], i, n;
    int main() {
        FILE* infile, *outfile;
        freopen_s(&infile,"in.txt","r",stdin);    //从in.txt中读取数据
        freopen_s(&outfile,"out.txt","w",stdout);  //输出到out.txt文件
        for (i = 0;cin >> a[i];i++);    //如果读到文件末,没数据读取就退出,注意句末有分号
        n = i;
        for (i = 0;i < n;i++)
            //cout << a[i] << '  ';
            cout << a[i] << endl;
        system("pause");
        return 0;
    }

    //读取文件到末尾
    //#pragma warning(suppress : 4996)
    #include "pch.h"
    #include <iostream>
    //#include <cstdlib>
    using namespace std;
    //#define _CRT_SECURE_NO_WARNINGS
    
    int a[5000], i, n;
    int main() {
        FILE* infile, *outfile;
        freopen_s(&infile,"in.txt","r",stdin);    //从in.txt中读取数据
        freopen_s(&outfile,"out.txt","w",stdout);  //输出到out.txt文件
        for (i = 0;cin >> a[i];i++);    //如果读到文件末,没数据读取就退出,注意句末有分号
        n = i;
        for (i = 0;i < n;i++)
            cout << a[i] << ' ';
            //cout << a[i] << endl;
        //system("pause");
        return 0;
    }

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int i,n,a[100];
      freopen("in.txt","r",stdin);
      freopen("out.txt","w",stdout);
      for(i=0; cin>>a[i]; i++);
      n=i;
      for(i=0; i<n; i++)
        cout<<a[i]<<endl;
      return 0;
    }

            方法二(FILE * ):

            此方法虽然要比方法一复杂,但该方法不属于文件重定向语句,且读取速度快,因此在比赛中推荐使用此方法。

                  FILE的说明:每个被使用的文件都在内存中开辟一个区,用来存放文件的有关信息(如文件的名字、文件状态及文件当前位置等)。这些信息是保存在一个结构体类型的变量中的。该结构体类型由系统定义,取名为FILE。文件读写完毕后需使用fclose函数关闭文件流。

            feof函数的说明:feof(in)中in是文件指针。它只有两个返回值。当遇到文件结束符(EOF)时返回1,否则返回0。所以第9行中!feof(in)的意思是,若feof(in)未遇到EOF,则一直执行for循环。

            fprintf函数和fscanf函数的说明:fprintf函数和fscanf函数是格式化读写函数,但读写对象为文件。

    //读写文件方法2
    #pragma warning(suppress:4996)
    #include "pch.h"
    #include <iostream>
    #include <cstdlib>
    #define _CRT_SECURE_NO_WARNINGS
    int main() {
        int i, len = 0, temp[100];
        FILE* infile,*outfile=NULL;
        //FILE* fp;
        errno_t err;
        //FILE* in, out;
        if ((err= fopen_s(&infile,"a.txt", "r"))!=0) {
        //if ((err = fopen_s(&fp, "a.txt", "r")) != 0) {
            //FILE* in = fopen_s(&infile, "a.txt", "r");   //指针指向输入文件
            //FILE* out = fopen_s(&outfile, "b.txt", "w"); //输出文件格式
        //if (( in = fopen_s(&infile, "a.txt", "r")) != NULL && (out = fopen_s(&outfile, "b.txt", "w")) != NULL) {
            fprintf(stderr, "***>Open error on input file a.txt");
            exit(1);
        }
        else if ((err = fopen_s(&outfile, "b.txt", "w")) != 0) {
        //else if ((err = fopen_s(&fp, "b.txt", "w")) != 0) {
            fprintf(stderr, "***>Open error on output file b.txt");
            exit(1);
        }
        else {
            fopen_s(&infile, "a.txt", "r");   //指针指向输入文件
            fopen_s(&outfile,"b.txt", "w"); //输出文件格式
            //fopen_s(&fp, "a.txt", "r");   //指针指向输入文件
            //fopen_s(&fp, "b.txt", "w"); //输出文件格式
        }
        //for (i = 0;!feof(in);i++) {      //如未到文件结尾
          for (i = 0;!feof(infile);i++) {      //如未到文件结尾
          //for (i = 0;!feof(fp);i++) {      //如未到文件结尾
            //fscanf_s(in,"%d",&temp[i]);    //读取文件中的数据
            fscanf_s(infile, "%d", &temp[i]);    //读取文件中的数据
            //fscanf_s(fp, "%d", &temp[i]);    //读取文件中的数据
            len++;
        }
        for (i = 0;i < len-1;i++) {      //写入文件
            //fprintf(out,"%d",&temp[i]);
             fprintf(outfile, "%d", temp[i]);
             //fprintf(fp, "%d", temp[i]);
        }
        //fclose(in);                      //关闭文件流
        //fclose(out);                     //关闭文件流
        if (infile != NULL && outfile != NULL) {
            fclose(infile);                      //关闭文件流
            fclose(outfile);                     //关闭文件流
        }
        //fclose(fp);//关闭文件流
        return 0;
    }

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int main()
    {
      int i,len,temp[100];
      //int i,len,temp[24];
      FILE* in = fopen("a.txt","r");
      FILE* out = fopen("b.txt","w");
      for(i=0; !feof(in); i++)
      {
        fscanf(in,"%d",&temp[i]);
        len++;
      }
      for(i=0; i<len-1; i++)
      {
        fprintf(out,"%d
    ",temp[i]);
      }
      fclose(in);
      fclose(out);
      return 0;
    }

    //读写文件方法2
    //#pragma warning(suppress:4996)
    #include "pch.h"
    #include <iostream>
    //#include <cstdlib>
    //#define _CRT_SECURE_NO_WARNINGS
    int main() {
        int i, len = 0, temp[100];
        FILE* infile,*outfile;
        //FILE* fp;
        errno_t err;
        //FILE* in, out;
        if ((err= fopen_s(&infile,"a.txt", "r"))!=0) {
        //if ((err = fopen_s(&fp, "a.txt", "r")) != 0) {
            //FILE* in = fopen_s(&infile, "a.txt", "r");   //指针指向输入文件
            //FILE* out = fopen_s(&outfile, "b.txt", "w"); //输出文件格式
        //if (( in = fopen_s(&infile, "a.txt", "r")) != NULL && (out = fopen_s(&outfile, "b.txt", "w")) != NULL) {
            fprintf(stderr, "***>Open error on input file a.txt");
            exit(1);
        }
        else if ((err = fopen_s(&outfile, "b.txt", "w")) != 0) {
        //else if ((err = fopen_s(&fp, "b.txt", "w")) != 0) {
            fprintf(stderr, "***>Open error on output file b.txt");
            exit(1);
        }
        else {
            //fopen_s(&infile, "a.txt", "r");   //指针指向输入文件
            //fopen_s(&outfile,"b.txt", "w"); //输出文件格式
            //fopen_s(&fp, "a.txt", "r");   //指针指向输入文件
            //fopen_s(&fp, "b.txt", "w"); //输出文件格式
        //}
        //for (i = 0;!feof(in);i++) {      //如未到文件结尾
            for (i = 0;!feof(infile);i++) {      //如未到文件结尾
            //for (i = 0;!feof(fp);i++) {      //如未到文件结尾
              //fscanf_s(in,"%d",&temp[i]);    //读取文件中的数据
                fscanf_s(infile, "%d", &temp[i]);    //读取文件中的数据
                //fscanf_s(fp, "%d", &temp[i]);    //读取文件中的数据
                len++;
            }
            for (i = 0;i < len;i++) {      //写入文件
                //fprintf(out,"%d",&temp[i]);
                fprintf(outfile, "%d", temp[i]);
                //fprintf(fp, "%d", temp[i]);
            }
            //fclose(in);                      //关闭文件流
            //fclose(out);                     //关闭文件流
            if (infile != NULL && outfile != NULL) {
                fclose(infile);                      //关闭文件流
                fclose(outfile);                     //关闭文件流
            }
            //fclose(fp);//关闭文件流
        }
        return 0;
    }

    #include <iostream>
    //#include <cstdlib>
    using namespace std;
    
    int main()
    {
      int i,len=0,temp[100];
      //int i,len,temp[24];
      FILE* in = fopen("a.txt","r");
      FILE* out = fopen("b.txt","w");
      for(i=0; !feof(in); i++)
      {
        fscanf(in,"%d",&temp[i]);
        len++;
      }
      for(i=0; i<len; i++)
      {
        fprintf(out,"%d",temp[i]);
      }
      fclose(in);
      fclose(out);
      return 0;
    }

           方法三(fstream):

           此方法使用了fstream头文件,推荐C++学习者使用。请看下例:

    //读写文件方法3
    #include "pch.h"
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main() {
        int a, b, c;
        //ifstream fin("in1.txt");
        //ofstream fout("out1.txt");
        ifstream in("in1.txt");
        ofstream out("out1.txt");
        //cin >> a >> b >> c;
        //cout <<a*b*c<< endl;
        //fin >> a >> b >> c;
        //fout <<a*b*c<< endl;
        in >> a >> b >> c;
        out << a * b*c << endl;
        //fin.close();
        //fout.close();
        in.close();
        out.close();
        return 0;
    }

    #include <fstream>
    using namespace std;
    
    int main()
    {
      int a,b,c;
      //ifstream in("in1.txt");
      //ofstream out("out1.txt");
      //in>>a>>b>>c;
      //out<<a*b*c<<endl;
      //in.close();
      //out.close();
      ifstream fin("in1.txt");
      ofstream fout("out1.txt");
      fin>>a>>b>>c;
      fout<<a*b*c<<endl;
      fin.close();
      fout.close();
      return 0;
    }

            方法四(fread函数):

            fread函数原型:size_tfread(void* buffer,size_tsize,size_tcount,FILE* in);

            (1)buffer:用于接收数据的地址(指针)。

            (2)size:单个元素的大小。单位是字节而不是位。

            (3)count:元素个数。

            (4)in:提供数据的文件指针。

            (5)返回值:读取的元素的个数。

            参考程序如下:

    //fread读取文件1
    #include "pch.h"
    #include <iostream>
    using namespace std;
    char a[1100000];
    int main() {
        FILE* in, *out;
        errno_t err;
        if ((err=fopen_s(&in,"a.in", "rb"))!=0) {
            fprintf(stderr, "***>Open error on input file a.in");
            exit(1);
        }else if ((err = fopen_s(&out, "b.out", "w")) != 0) {
            fprintf(stderr, "***>Open error on output file b.out");
            exit(1);
        }else {
            int n = fread(a, 1, 1100000, in);
            for (int i = 0;i < n;i++) {
                fprintf(out, "%c", a[i]);
            }
        }
        fclose(in);
        fclose(out);
        return 0;
    }

    #include <iostream>
    using namespace std;
    int a[1100000];
    int main()
    {
      FILE* in = fopen("a.in","rb");
      FILE* out = fopen("b.out","w");
      int len = fread(a,1,1100000,in);
      for(int i=0; i<len; i++)
      {
        fprintf(out,"%c",a[i]);
      }
      fclose(in);
      fclose(out);
      return 0;
    }

    #include <iostream>
    using namespace std;
    char a[1100000];
    int main()
    {
      FILE* in = fopen("a.in","rb");
      FILE* out = fopen("b.out","w");
      int len = fread(a,1,1100000,in);
      for(int i=0; i<len; i++)
      {
        fprintf(out,"%c",a[i]);
      }
      fclose(in);
      fclose(out);
      return 0;
    }

            fread()是按照char类型读取的,因此当读取的数据类型为数值时,需要再次转化为数值。参考程序如下:

    //fread读取文件2
    #include "pch.h"
    #include <iostream>
    //#include <stdlib.h>
    using namespace std;
    //FILE* in = fopen("i.txt","rb");
    FILE* in,*out;
    errno_t err;
    int mark = 0;
    char a1[21];
    int getnum() {     //将char类型转换为int型
        int obj= 0;
        while (!a1[mark]>='0'&&a1[mark]<='9') {
            mark++;
        }
        while (a1[mark]>='0'&&a1[mark]<='9') {
            obj = obj * 10 + a1[mark++]-'0';
        }
        return obj;
    }
    int main() {
        if ((err = fopen_s(&in, "i.txt", "rb")) != 0) {
            fprintf(stderr, "***>Open error on input file i.txt");
            exit(1);
        }else if((err=freopen_s(&out,"p.txt","w",stdout))!=0){ //文件输出
            fprintf(stderr, "***>Open error on output file p.txt");
            exit(1);
        }
        /*else if ((err = fopen_s(&out, "p.txt", "w")) != 0) {
            fprintf(stderr, "***>Open error on output file p.txt");
        }*/else {
            int i, s = 1, len = fread(a1, 1, 21, in);// 第二、第三个参数依据数组大小而定,够用就好
            //freopen("p.txt", "w", stdout);//文件输出
            //FILE* out = fopen("p.txt", "w");
            //freopen_s(&out,"p.txt", "w", stdout);
            //fopen_s(&out,"p.txt", "w");
            for (int i = 0;i < len;i++) {
                cout <<a1[i]<< endl;
            }
            for (i = 0;i < len;i++) {
                s *= getnum();
            }
            cout << len << endl;
            cout << s << endl;
            //fprintf(out,"%d",s);
            return 0;
        }
    }

    //fread读取文件2
    #include "pch.h"
    #include <iostream>
    //#include <stdlib.h>
    using namespace std;
    //FILE* in = fopen("i.txt","rb");
    FILE* in,*out;
    errno_t err;
    int mark = 0;
    char a1[21];
    int getnum() {     //将char类型转换为int型
        int obj= 0;
        while (!(a1[mark] >= '0'&&a1[mark] <= '9')) {
                mark++;
        }
        while (a1[mark] >= '0'&&a1[mark] <= '9') {
                obj = obj * 10 + a1[mark++] - '0';
        }
        return obj;
    }
    int main() {
        if ((err = fopen_s(&in, "i.txt", "rb")) != 0) {
            fprintf(stderr, "***>Open error on input file i.txt");
            exit(1);
        }else if((err=freopen_s(&out,"p.txt","w",stdout))!=0){ //文件输出
            fprintf(stderr, "***>Open error on output file p.txt");
            exit(1);
        }
        /*else if ((err = fopen_s(&out, "p.txt", "w")) != 0) {
            fprintf(stderr, "***>Open error on output file p.txt");
        }*/else {
            int i, s = 1, len = fread(a1, 1, 21, in);// 第二、第三个参数依据数组大小而定,够用就好
            //freopen("p.txt", "w", stdout);//文件输出
            //FILE* out = fopen("p.txt", "w");
            //freopen_s(&out,"p.txt", "w", stdout);
            //fopen_s(&out,"p.txt", "w");
            for (i = 0;i < len;i++) {
                //cout <<a1[i]<< endl;
                cout << a1[i];
            }
            for (i = 0;i < 10;i++) {
                //cout << getnum() << " ";
                  s  *= getnum();
            }
            cout << " " << len << " " << s;
            //fprintf(out,"%d",s);
            fclose(in);
            fclose(out);
            return 0;
        }
    }

    #include <iostream>
    //#include <stdlib.h>
    using namespace std;
    FILE* in = fopen("i.txt","rb");
    int mark=0;
    char a[21];
    int getnum()
    {
      int obj =0;
      while(!(a[mark]>='0'&& a[mark]<='9'))
        mark++;
      while(a[mark]>='0'&& a[mark]<='9')
        obj=obj*10+a[mark++]-'0';
      return obj;
    }
    int main()
    {
      freopen("p.txt","w",stdout);
      //FILE* out = fopen("p.txt","w");
      int i,s=1,n=fread(a,1,21,in);
      for(i=0; i<n; i++)
      {
        cout<< a[i] ;
        //fprintf(out,"%c",a[i]);
      }
      for(i=0; i<10; i++)
      {
        s *= getnum();
      }
      cout<< " " << n << " " << s << endl;
      //cout << s << endl;
      //fprintf(out," %d %d",n,s);
      fclose(in);
      //fclose(out);
      return 0;
    }

                          需要注意的是,无论何种文件读写方法,最后一行万万不可写getchar()或system("pause")之类的语句,因为这类语句是在等待用户再输入一个字符。而文件读写形式的程序,是不需要暂停的。

            四种文件读写方法的比较如表3.1所示。

            表   3.1

    读写方法 freopen FILE* fstream fread
    读写速度

    <iostream>下使用cin和cout

    这些标准输入输出流速度会慢;

    <stdio.h>下使用fscanf和fprintf

    这些专门读写文件的函数速度会快。

    C语言专用。

    速度快。

    C++专用。速度快。

    堪称最精确最快的读文件方式之一。精确到连空格都可以读。因为它是连着整个文件读所以速度快。

    占用内存 前者较大,后者较小。 较小 较大。 较大

            读取10万个数据(0<=数据<=399)并重新写入文件的测试比较如表3.2所示(其评测环境为Cena)。


             读写函数

             fputs与fgets函数

             fgets的功能是在文件中读一行字符串。它有三个参数。

            例如fgets(a,n,in);其中a是一个char型数组用于存放读取的字符串,n表示读取n~1个字符,in是文件读入指针。

            fgets函数会在读入的数据末尾加上一个空字符以构成一个字符串。

            fgets与gets的不同之处在于,fgets读取到换行符后不会将其省略,而gets读到换行符时会退出,并会将换行符略去。

           fputs的功能是在文件中写入一行字符串。它有两个参数。

           例如,fputs(a,out);其中a是一个要输出的char型数组,out是文件输出指针。

           fputs与puts的不同之处是fputs在打印时并不添加换行符。

           参考程序如下所示:

    #include "pch.h"
    #include <iostream>
    using namespace std;
    char a2[22];
    FILE* infile, *outfile;
    int main() {
        int i;
        fopen_s(&infile,"i.txt","rb");
        fopen_s(&outfile,"o.txt","w");
        fgets(a2,22,infile);
        fputs(a2,outfile);
        for (i = 0;i < sizeof(a2);i++) {
            fprintf(outfile, "%c", a2[i]);
        }
        return 0;
     }

    #include <iostream>
    using namespace std;
    char a[22];
    int i;
    int main()
    {
      FILE* in = fopen("i.txt","rb");
      FILE* out = fopen("o.txt","w");
      fgets(a,22,in);
      fputs(a,out);
      for(i=0; i<sizeof(a); i++)
      {
        fprintf(out,"%c",a[i]);
      }
      return 0;
    }

                   getc与putc函数

             getc函数的功能是从文件中读出一个字符。

            常用的判断文件是否读取结束的语句为:(ch=getc(fp))!=EOF)。EOF为文件结束标志。文件也可以被理解为一种流,故当文件输入指针为in时,getc(in)就等同于getchar()了。

           putc函数的功能是把字符ch写到文件中去。

           如果文件输出指针为out,则putc(out)就等同于putchar()了。

           参考程序如下所示:

    #include "pch.h"
    //#include <stdio.h>
    #include <iostream>
    using namespace std;
    FILE* ingetc, *outputc;
    int main(){
        fopen_s(&ingetc,"igetc.txt", "rb");
        fopen_s(&outputc, "oputc.txt", "w");
        char c; 
        c = getc(ingetc);
        putc(c,outputc);
        fclose(ingetc);
        fclose(outputc);
        return 0;
    }

    #include <iostream>
    using namespace std;
    int main()
    {
      FILE* in  = fopen("igetc.txt","rb");
      FILE* out = fopen("oputc.txt","wb");
      char c;
      c= getc(in);
      putc(c,out);
      fclose(in);
      fclose(out);
      return 0;
    }

            fgetc与fputc函数

            fgetc函数的功能是从fp的当前位置读取一个字符。

           例如,fgetc(in);其中in是文件读入指针。

            fputc函数的功能是将ch写入fp当前指定位置。

           例如,fputc(ch,out);其中,ch是要输出的字符,out是文件输出指针。

           fscanf与fprintf函数

           fscanf的功能是按照指定格式从文件中出读入数据。

           fprintf的功能是将格式化数据(这里的格式化是即按照指定格式)写入文件中。

                         有一道题,要求读取一行字符串,可是该字符串包含有空格,例如“I am a student”,如果使用通常的读写方法,当读到空格时,读写语句就会认为该字符串已经结束。那么,有什么好的办法读取含空格的字符串呢?

                   在实际应用中,有下列几种方法可以读入包括空格符的字符串。

                   1. 用gets读取。

    //gets读字符串
    #include "pch.h"
    #include <iostream>
    using namespace std;
    int main() {
        char a[100];
        gets_s(a);
        cout << a << endl;
        system("pause");
        return 0;
    }

    #include <iostream>
    using namespace std;
    
    int main()
    {
      char a[100];
      gets(a);
      cout<<a<<endl;
      return 0;
    }

                   2. 用getline(cin,string)来读入一行包含空格符的字符串。

    //getline读字符串
    #include "pch.h"
    #include <iostream>
    #include <string>
    using namespace std;
    int main() {
        string str;
        getline(cin, str);
        cout << str << endl;
        system("pause");
        return 0;
    }

    #include <iostream>
    using namespace std;
    
    int main()
    {
      string str;
      getline(cin,str);
      cout<<str<<endl;
      return 0;
    }

                    3.cin.getline(字符指针,字符个数,结束符)。结束符默认是' '。

    //cin.getline读字符串
    #include "pch.h"
    #include <iostream>
    using namespace std;
    int main()
    {
        char a[80];
        cin.getline(a,80,'
    ');
        cout << a << endl;
        system("pause");
        return 0;
    }

    #include <iostream>
    using namespace std;
    
    int main()
    {
      char a[80];
      cin.getline(a,80,'
    ');
      cout<<a<<endl;
      system("pause");
      return 0;
    }

                   4. 用循环语句来判断是否读完这一行,否则读取这一字符。

    #include "pch.h"
    #include <iostream>
    using namespace std;
    int main() {
        char ch;
        /*
        while ((ch = getchar()) != '
    ') {
            putchar(ch);
        }
        */
        while ((ch = cin.get()) != '
    ') {
            cout.put(ch);
        }
        system("pause");
        return 0;
    }

    #include <iostream>
    using namespace std;
    
    int main()
    {
      char ch;
      /*while((ch=getchar())!='
    ')
      {
        putchar(ch);
      }*/
      while((ch=cin.get())!='
    ')
      {
        cout.put(ch);
      }
      system("pause");
      return 0;
    }

                   Ch=fin.get();这是在文件流读写中使用的,是获得单个字符。

             

    //fin.get()使用
    #include "pch.h"
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main() {
        int a, b, c,space;
        ifstream fin("fin.txt");
        a = fin.get() - '0';
        space = fin.get();
        b = fin.get() - '0';
        space = fin.get();
        c = fin.get() - '0';
        cout<<a<<b<<c<<endl;
        ofstream fout("fout.txt");
        //fout.put(char(a)).put(char(b)).put(char(c));
        fout.put(a).put(b).put(c);
        fout << a << b << c;
        fin.close();
        fout.close();
        return 0;
    }

     

     

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
      int a,b,c,space;
      ifstream fin("fin.txt");
      a=fin.get()-'0';
      space=fin.get();
      b=fin.get()-'0';
      space=fin.get();
      c=fin.get()-'0';
      cout<<a<<b<<c;
      ofstream fout("fout.txt");
      fout.put(a).put(b).put(c);
      fout<<a<<b<<c;
      fin.close();
      fout.close();
      return 0;
    }

                   产生随机数据

                      有些测试数据必须手工制作,以防止某些特例的出现,但是除此之外的多数测试数据,如果能写一个程序自动产生该有多好!这显然需要随机数函数的帮忙了。

          【例题描述】趣味摇奖机

            魔法学院举行游园活动,为了烘托节日气氛,决定在活动中设一个如图3.7所示的趣味摇奖机,游戏规则如下:计算机在0~9十个数字中随机取出一个数,由学生去猜,猜中的获特等奖,相差一个数的,获一等奖,相差两个数的,获二等奖,相差三个数的获三等奖,其余的没有奖。现在,请你来编写这个程序实现这个功能。

    #include "pch.h"
    #include <iostream>
    //#include <math.h>  
    //#include <cmath>
    #include <cstdlib>
    //#include <stdlib.h>  //C语言中常用的头文件,包含了常用的系统函数
    #include <time.h>     //必须使用time类的头文件
    using namespace std;
    int main() {
    
        int j, t;
        t = time(0) % 10;
        cout << time(0) << t;
        cin >> j;
    
        if (j >= 0 && j <= 9) {
            if (abs(j - t) == 0) {
                cout << "特等奖";
            }
            else if (abs(j - t)==1) {
                cout << "一等奖";
            }
            else if (abs(j - t) == 2) {
                cout << "二等奖";
            }
            else if (abs(j - t) == 3) {
                cout << "三等奖";
            }
            else {
                cout << "什么奖都没有";
            }
        }
        system("pause");
        return 0;
    }

    #include <iostream>
    //#include <math.h>
    //#include <cmath>
    //#include <cstdlib>
    #include <stdlib.h>
    #include <time.h>
    using namespace std;
    
    int main()
    {
      int j,t;
      t=time(0)%10;
      cout<<time(0)<<t;
      cin>>j;
      if(j>=0&&j<=9)
      {
        if(abs(j-t)==0)
        {
          cout<<"特等奖";
        }
        else if(abs(j-t)==1)
        {
          cout<<"一等奖";
        }
        else if(abs(j-t)==2)
        {
          cout<<"二等奖";
        }
        else if(abs(j-t)==3)
        {
          cout<<"三等奖";
        }
        else
        {
          cout<<"什么奖也没有";
        }
      }
      system("pause");
      return 0;
    }

                                            哈哈,我得了N个特等奖,获得了N个高阶的魔法卷轴。这是因为我发现这个程序通过获取当前时间来生成随机数的方法有一定的规律性,我只要估算好时间,就可以算出下一个数的大致范围。

            上面的程序中产生的随机数,一般称为伪随机数,真随机数的使用方法如下例所以(C++已默认包含time类的函数):

    //真随机数
    #include "pch.h"
    #include <iostream>
    #include <stdlib.h>
    #include <time.h>
    using namespace std;
    int main() {
        int j, t;
        srand(time(0));
        t = rand()%10;
        cout << rand();
        cout << t;
        cin >> j;
        if (0<=j<=9) {
            if (abs(j-t)==0) {
                cout<<"特等奖";
            }
            else if (abs(j-t)==1) {
                cout<<"一等奖";
            }
            else if (abs(j-t)==2) {
                cout<<"二等奖";
            }
            else if(abs(j-t)==3){
                cout << "三等奖";
            }
            else {
                cout << "没有奖";
            }
        }
    
        system("pause");
        return 0;
    }

    //真随机数
    #include "pch.h"
    #include <iostream>
    #include <stdlib.h>
    #include <time.h>
    using namespace std;
    int main() {
        int j, t;
        //srand(time(0));
        srand((unsigned) time(NULL));   //获取随机数种子,rand()产生0~32767之间的数
        t = rand()%10;
        cout << rand();
        cout << t;
        cin >> j;
        if (0<=j<=9) {
            if (abs(j-t)==0) {
                cout<<"特等奖";
            }
            else if (abs(j-t)==1) {
                cout<<"一等奖";
            }
            else if (abs(j-t)==2) {
                cout<<"二等奖";
            }
            else if(abs(j-t)==3){
                cout << "三等奖";
            }
            else {
                cout << "没有奖";
            }
        }
    
        system("pause");
        return 0;
    }

    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    using namespace std;
    
    int main()
    {
      int j,t;
      srand(time(0));
      t=rand()%10;
      cout<<rand();
      cout<<t;
      cin>>j;
      if(j<0||j>9)
      {
        return 0;
    
      }
      else
      {
        if(abs(j-t)==0)
        {
          cout<<"特等奖";
        }
        else if(abs(j-t)==1)
        {
          cout<<"一等奖";
        }
        else if(abs(j-t)==2)
        {
          cout<<"二等奖";
        }
        else if(abs(j-t)==3)
        {
          cout<<"三等奖";
        }
        else
        {
          cout<<"没有奖";
        }
      }
      system("pause");
      return 0;
    }

    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    using namespace std;
    
    int main()
    {
      int j,t;
      //srand(time(0));
      srand((unsigned)time(NULL));//获取随机数种子,rand()产生0~32767之间的数
      t=rand()%10;
      cout<<rand();
      cout<<t;
      cin>>j;
      if(j<0||j>9)
      {
        return 0;
    
      }
      else
      {
        if(abs(j-t)==0)
        {
          cout<<"特等奖";
        }
        else if(abs(j-t)==1)
        {
          cout<<"一等奖";
        }
        else if(abs(j-t)==2)
        {
          cout<<"二等奖";
        }
        else if(abs(j-t)==3)
        {
          cout<<"三等奖";
        }
        else
        {
          cout<<"没有奖";
        }
      }
      system("pause");
      return 0;
    }

     

           生成0~1之间的随机整数:

  • 相关阅读:
    bzoj 5455
    hdu 6705
    hdu 6706
    斜率优化
    bzoj3672
    bzoj1367
    bzoj2118
    bzoj2337
    Codeforces 1077D Cutting Out(二分答案)
    Codeforces 1079C Playing Piano(记忆化搜索)
  • 原文地址:https://www.cnblogs.com/ZHONGZHENHUA/p/10520567.html
Copyright © 2011-2022 走看看