防范arp欺骗:构造一个类似printf的函数,输出到字符串

来源:百度文库 编辑:高校问答 时间:2024/05/06 03:10:05
printf可以可变参数输入,类似
printf("my name is %s","Nicky");
如何构造一个类似printf的函数使其结果输出到一个字符串?

#include <iostream.h>

void MyPrint(const char *s,const char *sIn)
{
/******************************************
input : s: format sIn,nubers,list,strings,and soon which
separated by ',',
Examples:
s = "%d is %s", sIn = "3,my favorite number;"
output : 3 is my favorite number;
but only one single formation letter is permited
exceptions: %lf cannot be known by this simple implement
this is only one simulation for the print

*****************************************/
int i = 0;
int nIndex = 0;
int nResultIndex = 0;
char sResult[50];
while(s[i]!='\0')
{
if(s[i]=='%')// no detect the type for simpfied
{
i = i+2;
while(sIn[nIndex]!='\0'&&sIn[nIndex]!=',')
{
sResult[nResultIndex++] = sIn[nIndex++];
}
nIndex++;
}
sResult[nResultIndex++] = s[i];
i++;
}
sResult[nResultIndex] = '\0';
cout<<sResult<<endl;
//return sResult;
}

void main()
{

MyPrint("%d is %s!!","3,my favorite number");

}

// crt_sprintf.c
/* This program uses sprintf to format various
* data and place them in the string named buffer.
*/

#include <stdio.h>

int main( void )
{
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f;

/* Format and print various data: */
j = sprintf( buffer, " String: %s\n", s );
j += sprintf( buffer + j, " Character: %c\n", c );
j += sprintf( buffer + j, " Integer: %d\n", i );
j += sprintf( buffer + j, " Real: %f\n", fp );

printf( "Output:\n%s\ncharacter count = %d\n", buffer, j );
}
Output
Output:
String: computer
Character: l
Integer: 35
Real: 1.732053

character count = 79

有个叫sprintf的,
char tmp[255];
sprintf(tmp, "my name is %s", "Nicky");