C++fread/fwrite的基础用法

前言

fread是吼东西

应某人要求(大概)科普一下

fread

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
using namespace std;

char st[233];
char *Ch=st;

int main()
{
    fread(st,1,233,stdin);
    cout<<st<<endl;
    cout<<*Ch<<endl;
}

可以用文件输入,也可以直接输并在最后加Ctrl+Z

(下面的空行是因为读入了一个换行符)

fread基本格式:

fread(字符串,1,字符串大小,stdin);

*Ch一开始指向的是st[0],之后可以不断*++Ch来往后跳

快速读入

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
using namespace std;

char st[233];
char *Ch=st;

int getint()
{
    int x=0;
    
    while (*Ch<'0' || *Ch>'9') *++Ch;
    while (*Ch>='0' && *Ch<='9') x=x*10+(*Ch-'0'),*++Ch;
    
    return x;
}

int main()
{
    fread(st,1,233,stdin);
    cout<<getint()<<endl;
}

fwrite

用处并不是很大

fwrite(字符串,1,字符串长度,stdout);

快速输出

把数字转成字符串再反过来加进去(要加上空格/换行符)

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#define fo(a,b,c) for (a=b; a<=c; a++)
#define fd(a,b,c) for (a=b; a>=c; a--)
using namespace std;

char st[233];
int Len;

void putint(int x)
{
    int a[233];
    int i,len=0;
    
    if (!x) len=1;
    while (x)
    {
        a[++len]=x%10;
        x/=10;
    }
    
    fd(i,len,1)
    st[++Len]=a[i]+'0';
    st[++Len]=' ';
}

int main()
{
    Len=-1;
    putint(1);
    putint(2);
    putint(233);
    
    fwrite(st,1,Len,stdout);
}

猜你喜欢

转载自www.cnblogs.com/gmh77/p/11795417.html