C语言
自己定义的myprintf 请问为什么打印不出来汉字,以下是代码以及报错信息;#include <stdio.h>
#include "stdarg.h"
#include "math.h"
#include "stdlib.h"
#include "string.h"
void printInt(int num)
{
int dec = 1;
int temp;
if(num < 0)
{
putchar('-');
num = -num;
}
temp = num;
while(temp > 9)
{
temp /= 10;
dec *= 10;
}
while(dec > 0)
{
putchar(num / dec + '0');
num = num % dec;
dec /= 10;
}
}
int countInt(int num)
{
int count = 0;
if(num < 0)
{
count++;
num = -num;
}
do
{
count++;
}while(num /= 10);
return count;
}
int printStr(char *str)
{
int i = 0;
while(str != '\0')
{
putchar(str);
}
return i;
}
int myprintf(char *format,...)
{
int i = 0;
int count = 0;
int darg;
char carg;
char *sarg;
va_list(vap);
va_start(vap, format);
while(format != '\0')
{
if(format != '%')
{
putchar(format);
count++;
}
else
{
switch(format)
{
case 'd':
{
darg = va_arg(vap, int);
printInt(darg);
count += countInt(darg);
break;
}
case 'c':
{
carg = va_arg(vap, int);
putchar(carg);
count++;
break;
}
case 's':
{
sarg = va_arg(vap, char *);
printStr(sarg);
count += strlen(sarg);
break;
}
}
i += 2;
}
}
va_end(vap);
return count;
}
void main()
{
int num = 24;
char *str = "Win";
int i;
i = myprintf("wo%d==%s", str);
myprintf("打印了%d个字符。", i);
}
问题出在printStr函数上,该函数使用了putchar函数来打印字符,但是putchar函数只能打印ASCII码对应的字符,无法打印汉字。解决方法是使用puts函数来打印字符串,因为puts函数可以打印包含汉字的字符串。
修改printStr函数如下:
int printStr(char *str)
{
puts(str);
return strlen(str);
}
这样就可以正确打印出汉字了。 本帖最后由 1436466587 于 2023-11-8 16:24 编辑
isdkz 发表于 2023-11-8 16:11
问题出在printStr函数上,该函数使用了putchar函数来打印字符,但是putchar函数只能打印ASCII码对应的字符 ...
修改后未解决,还是报错老哥
#include <stdio.h>
#include "stdarg.h"
#include "math.h"
#include "stdlib.h"
#include "string.h"
void printInt(int num)
{
int dec = 1;
int temp;
if(num < 0)
{
putchar('-');
num = -num;
}
temp = num;
while(temp > 9)
{
temp /= 10;
dec *= 10;
}
while(dec > 0)
{
putchar(num / dec + '0');
num = num % dec;
dec /= 10;
}
}
int countInt(int num)
{
int count = 0;
if(num < 0)
{
count++;
num = -num;
}
do
{
count++;
}while(num /= 10);
return count;
}
int printStr(char *str)
{
int i = 0;
while(str != '\0')
{
puts(str);
}
return i;
}
int myprintf(char *format,...)
{
int i = 0;
int count = 0;
int darg;
char carg;
char *sarg;
va_list(vap);
va_start(vap, format);
while(format != '\0')
{
if(format != '%')
{
puts(format);
count++;
}
else
{
switch(format)
{
case 'd':
{
darg = va_arg(vap, int);
printInt(darg);
count += countInt(darg);
break;
}
case 'c':
{
carg = va_arg(vap, int);
putchar(carg);
count++;
break;
}
case 's':
{
sarg = va_arg(vap, char *);
printStr(sarg);
count += strlen(sarg);
break;
}
}
i += 2;
}
}
va_end(vap);
return count;
}
页:
[1]