|
50鱼币
在最前面
在中间
就是遇到字符串就出错
#include <stdio.h>
#include <stdarg.h>
int int_print(int d);
int str_print(char *s);
int wdpritnf(char *s, ...);
int int_print(int d){
int i = 0, j = 1, ls, count = 0;
if(d < 0){
putchar('-');
d = -d;
count++;
}
ls = d;
while (ls > 9){
j *= 10;
ls /= 10;
}
while (d > 0){
putchar(d / j + '0');
d = d % j;
j = j / 10;
count++;
}
return count;
}
int str_print(char *s){
int i = 0;
while (s[i] != '\0'){
putchar(s[i]);
i++;
}
return i;
}
int wdprintf(char *s, ...){
int d, i = 0, count = 0;
char c;
va_list in;
va_start(in, s);
while (s[i] != '\0'){
if (s[i] == '%'){
switch (s[++i]){
case 'd':{
d = va_arg(in, int);
count += int_print(d);
break;
}
case 'c':{
c = va_arg(in, int);
putchar(c);
count++;
break;
}
case 's':{
s = va_arg(in, char *);
count += str_print(s);
break;
}
}
i++;
}
else{
putchar(s[i]);
i++;
count++;
}
}
return count;
va_end(in);
}
int main(){
int d, i;
char c;
char *s;
wdprintf("请输入一个字符串:");
scanf("%s",s);
i = wdprintf("这个字符串是%s\n",s);
wdprintf("请输入一个字符:");
scanf("%c",&c);
i = wdprintf("这个字符是%c\n",c);
wdprintf("请输入一个数字:");
scanf("%d",&d);
i = wdprintf("这个数字是%d\n",d);
return 0;
}
不知道为什么。
本帖最后由 jackz007 于 2022-11-22 02:05 编辑
我也折腾了 3+ 个小时,不过,可变参数函数,我是从 0 开始学的,现炒现卖。
- #include <stdio.h>
- #include <stdarg.h>
- int int_print(int d)
- {
- int i = 0, j = 1, ls, count = 0;
- if(d < 0){
- putchar('-');
- d = -d;
- count++;
- }
- ls = d;
- while (ls > 9){
- j *= 10;
- ls /= 10;
- }
- while (d > 0){
- putchar(d / j + '0');
- d = d % j;
- j = j / 10;
- count++;
- }
- return count;
- }
- int str_print(const char * s)
- {
- int i = 0 ;
- while (s[i] != '\0'){
- putchar(s[i]) ;
- i ++ ;
- }
- return i ;
- }
- int wdprintf(const char * s , ...)
- {
- int d , i = 0 , count = 0 ;
- char c , * cp ;
- va_list in ;
- va_start(in , s) ;
- while (s[i]) {
- if (s[i] == '%') {
- switch (s[++ i]) {
- case 'd': d = va_arg(in , int) ;
- count += int_print(d) ;
- break ;
- case 'c': c = va_arg(in , int) ;
- putchar(c) ;
- count ++ ;
- break ;
- case 's': cp = va_arg(in , char *) ; // 指针 cp 不可以用 s
- count += str_print(cp) ; // 指针是 cp
- break ;
- }
- } else {
- putchar(s[i]) ;
- count ++ ;
- }
- i ++ ;
- }
- va_end(in) ;
- return count ;
- }
- int main()
- {
- int d, i ;
- char c ;
- char s[512] ;
- wdprintf("请输入一个字符串:") ;
- scanf("%s%*c" , s) ;
- i = wdprintf("这个字符串是:%s\n" , s) ;
- wdprintf("请输入一个字符:") ;
- scanf("%c", & c) ;
- i = wdprintf("这个字符是:%c\n" , c) ;
- wdprintf("请输入一个数字:") ;
- scanf("%d", & d) ;
- i = wdprintf("这个数字是: %d\n",d) ;
- return 0 ;
- }
复制代码
以后求助请把代码贴进代码框,否则,光*屁*股丢在外面有些代码会被列为页面描述指令而被过滤掉,比如,常见的 [ i ] 就停不住。
|
最佳答案
查看完整内容
我也折腾了 3+ 个小时,不过,可变参数函数,我是从 0 开始学的,现炒现卖。
以后求助请把代码贴进代码框,否则,光*屁*股丢在外面有些代码会被列为页面描述指令而被过滤掉,比如,常见的 [ i ] 就停不住。
|