题意:给出输入格式,判断它的参数是否相匹配。
* %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;
}