| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
#include <stdio.h> 
#include <stdarg.h> 
#include <string.h> 
int myprintf(char *n,...); 
int myprintf(char *n,...) 
{ 
        int i = 0; 
        int sum = 0; 
        char *p; 
        va_list vap; 
        va_start(vap,n);//n是字符串名,即字符串的首个字符的地址  
        while(*n != '\0') 
        { 
        if(*n == '%') 
        { 
                if(*n+1 == 's') 
                { 
                         
                p = va_arg(vap,char *); 
                while(*p != '\0') 
                { 
                        putchar(*p); 
                        *p++; 
                } 
                //else if(*n+1 == 'd') 
                } 
 
        putchar(*n); 
        *n++; 
        } 
        } 
        va_end(vap); 
        return 1;//返回一共有多少个字母  
} 
 
int main(void) 
{ 
        int i; 
        myprintf("hello %s %s","ab","cd"); 
         
        return 0; 
} 
各位大佬,请教一下,这段代码我想实现自己定义的myprintf函数的可变参数的输出(是否输出字符个数不重要),参照SIE30可变参数答案更改之后也无法输出,请问为什么?
- #include <stdio.h>
 
 - #include <stdarg.h>
 
 - #include <string.h>
 
  
- int myprintf(char *n, ...);
 
  
- int myprintf(char *n, ...) {
 
 -     int count = 0;
 
 -     char *p;
 
 -     va_list vap;
 
 -     va_start(vap, n);
 
 -     while (*n != '\0') {
 
 -         if (*n == '%') {
 
 -             if (*(n + 1) == 's') {
 
 -                 p = va_arg(vap, char *);
 
 -                 while (*p != '\0') {
 
 -                     putchar(*p);
 
 -                     p++;
 
 -                     count++;
 
 -                 }
 
 -                 n += 2; // 跳过%s
 
 -             }
 
 -         } else {
 
 -             putchar(*n);
 
 -             n++;
 
 -             count++;
 
 -         }
 
 -     }
 
 -     va_end(vap);
 
 -     return count;
 
 - }
 
  
- int main(void) {
 
 -     int i;
 
 -     myprintf("hello %s %s", "ab", "cd");
 
 -     return 0;
 
 - }
 
 
  复制代码 
 
更改后的代码应该可以正确输出"hello ab cd"。主要问题在于原始代码中的 if(*n+1 == 's') 这行有误,应该改为 if (*(n + 1) == 's') 。另外,在处理完%s时,应该将n向后移动两位,以跳过%s,否则会陷入死循环。 
 
 
 |   
 
 
 
 |