Iterate through char array and print chars

梦想的初衷 提交于 2019-12-10 17:14:01

问题


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.

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;
}

回答1:


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.




回答2:


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

#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;
}


来源:https://stackoverflow.com/questions/19062804/iterate-through-char-array-and-print-chars

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!