遍历字符数组并打印字符 [英] Iterate through char array and print chars
本文介绍了遍历字符数组并打印字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打印变量中的每个字符.
I am trying to print each char in a variable.
我可以通过更改为这个 printf("Value: %d
", d[i]);
来打印 ANSI 字符编号,但我无法实际打印字符串字符本身.
I can print the ANSI char number by changing to this printf("Value: %d
", d[i]);
but am failing to actually print the string character itself.
我在这里做错了什么?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int len = strlen(argv[1]);
char *d = malloc (strlen(argv[1])+1);
strcpy(d,argv[1]);
int i;
for(i=0;i<len;i++){
printf("Value: %s
", (char)d[i]);
}
return 0;
}
推荐答案
您应该使用 %c
格式来打印 C 中的字符.您使用的是 %s
,其中需要使用指向字符串的指针,但在您的情况下,您提供的是整数而不是指针.
You should use %c
format to print characters in C. You are using %s
, which requires to use pointer to the string, but in your case you are providing integer instead of pointer.
这篇关于遍历字符数组并打印字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文