C语言 遍历字符数组并打印字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19062804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:34:18  来源:igfitidea点击:

Iterate through char array and print chars

cstringansi

提问by ojhawkins

I am trying to print each char in a variable.

我正在尝试打印变量中的每个字符。

I can print the ANSI char number by changing to this printf("Value: %d\n", d[i]);but am failing to actually print the string character itself.

我可以通过更改为这个来打印 ANSI 字符号,printf("Value: %d\n", d[i]);但实际上无法打印字符串字符本身。

What I am doing wrong here?

我在这里做错了什么?

#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\n", (char)d[i]);
} 
    return 0;
}

回答by mvp

You should use %cformat 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.

您应该使用%cformat 在 C 中打印字符。您正在使用%s,这需要使用指向字符串的指针,但在您的情况下,您提供的是整数而不是指针。

回答by Tay Wee Wen

The below will work. You pass in the pointer to a string when using the token %s in printf.

下面将工作。在 printf 中使用标记 %s 时,您传递指向字符串的指针。

#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]);

  printf("Value: %s\n", d);
  return 0;
}