在C++里用printf这样的C函数是不是很没面子
答案:2 悬赏:30 手机版
解决时间 2021-01-28 08:16
- 提问者网友:相思似海深
- 2021-01-28 04:36
在C++里用printf这样的C函数是不是很没面子
最佳答案
- 五星知识达人网友:酒安江南
- 2021-01-28 05:54
都学c++的!为什么不用cout!!简单多的!!!用printf只会让别人觉得太low的!!暴露自己是新手
全部回答
- 1楼网友:妄饮晩冬酒
- 2021-01-28 07:16
这是从linux内核0.11找的,可以参考一下
151 static int printf(const char *fmt, ...)
152 {
153 va_list args;
154 int i;
155
156 va_start(args, fmt);
157 write(1,printbuf,i=vsprintf(printbuf, fmt, args));
158 va_end(args);
159 return i;
160 }
int vsprintf(char *buf, const char *fmt, va_list args)
{
int len;
int i;
char * str;
char *s;
int *ip;
int flags;
int field_width;
int precision;
int qualifier;
for (str=buf ; *fmt ; ++fmt) {
if (*fmt != '%') {
*str++ = *fmt;
continue;
}
flags = 0;
repeat:
++fmt;
switch (*fmt) {
case '-': flags |= left; goto repeat;
case '+': flags |= plus; goto repeat;
case ' ': flags |= space; goto repeat;
case '#': flags |= special; goto repeat;
case '0': flags |= zeropad; goto repeat;
}
field_width = -1;
if (is_digit(*fmt))
field_width = skip_atoi(&fmt);
else if (*fmt == '*') {
field_width = va_arg(args, int);
if (field_width < 0) {
field_width = -field_width;
flags |= left;
}
}
precision = -1;
if (*fmt == '.') {
++fmt;
if (is_digit(*fmt))
precision = skip_atoi(&fmt);
else if (*fmt == '*') {
precision = va_arg(args, int);
}
if (precision < 0)
precision = 0;
}
qualifier = -1;
if (*fmt == 'h' || *fmt == 'l' || *fmt == 'l') {
qualifier = *fmt;
++fmt;
}
switch (*fmt) {
case 'c':
if (!(flags & left))
while (--field_width > 0)
*str++ = ' ';
*str++ = (unsigned char) va_arg(args, int);
while (--field_width > 0)
*str++ = ' ';
break;
case 's':
s = va_arg(args, char *);
len = strlen(s);
if (precision < 0)
precision = len;
else if (len > precision)
len = precision;
if (!(flags & left))
while (len < field_width--)
*str++ = ' ';
for (i = 0; i < len; ++i)
*str++ = *s++;
while (len < field_width--)
*str++ = ' ';
break;
case 'o':
str = number(str, va_arg(args, unsigned long), 8,
field_width, precision, flags);
break;
case 'p':
if (field_width == -1) {
field_width = 8;
flags |= zeropad;
}
str = number(str,
(unsigned long) va_arg(args, void *), 16,
field_width, precision, flags);
break;
case 'x':
flags |= small;
case 'x':
str = number(str, va_arg(args, unsigned long), 16,
field_width, precision, flags);
break;
case 'd':
case 'i':
flags |= sign;
case 'u':
str = number(str, va_arg(args, unsigned long), 10,
field_width, precision, flags);
break;
case 'n':
ip = va_arg(args, int *);
*ip = (str - buf);
break;
default:
if (*fmt != '%')
*str++ = '%';
if (*fmt)
*str++ = *fmt;
else
--fmt;
break;
}
}
*str = '\0';
return str-buf;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯