POJ 3428 Formatting function (文件输入)

题意:给出输入格式,判断它的参数是否相匹配。

* %s — argument as a string
* %d — argument as an integer value, without any leading zeroes
* %% — literal '%' character

Formatting error is generated if:

* number of arguments required by format specifiers is not equal to the number of actually supplied arguments,
* argument for %d specifier contains non-digit character.
* '%' character in format string is not followed by either '%', 's' or 'd'.

题解:比较有特色的是本题用的是文件输入,学习了。

#include<cstdio>
#include<cctype>
#include<cstring>
using namespace std;

char format[50010];
char args[1001][50010];

bool judgeInt(char str[]) //判断是否是数字
{
    if(str[0] == '\0' || str[0] == '\n') //空串
        return false;
    for(int i = 0; str[i] != '\0' && str[i] != '\n'; i++)
        if(!isdigit(str[i])) return false; //含有非数字的字符
    return true;
}

void printInt(char str[])
{
    int i = 0;
    while(str[i] == '0') i++; //去掉前缀0
    if(str[i] == '\0' || str[i] == '\n') { putchar('0'); return; }
    while(str[i] != '\0' && str[i] != '\n') printf("%c",str[i++]);
}

void printStr(char str[])
{
    for(int i = 0; str[i] != '\0' && str[i] != '\n'; i++)
        printf("%c",str[i]);
}

int calArgs(char format[], char args[][50010]) //计算输入的参数的个数
{
    int k = 0;
    for(int i = 0; format[i] != '\0' && format[i] != '\n'; i++)
    {
        if(format[i] == '%')
        {
            i++;
            if(format[i] == 'd' && judgeInt(args[k])) k++;
            else if(format[i] == 's') k++;
            else if(format[i] == '%') continue;
            else return -1; //1表示Error
        }
    }
    return k;
}

void output(char format[], char args[][50010]) //输出
{
    int k = 0;
    for(int i = 0; format[i] != '\0' && format[i] != '\n'; i++)
    {
        if(format[i] == '%')
        {
            i++;
            if (format[i] == 'd' ) printInt(args[k++]);
            else if(format[i] == 's') printStr(args[k++]);
            else putchar('%');
        }
        else printf("%c",format[i]);
    }
    printf("\n");
}

int main()
{
    int sum = 0; //参数的个数
    fgets(format,50010,stdin);
    while (fgets(args[sum],50010,stdin)) sum++;
    if(calArgs(format,args) != sum) printf("ERROR");
    else output(format, args);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值