Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through char array and print chars

Tags:

c

string

ansi

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;
}
like image 865
ojhawkins Avatar asked Sep 28 '13 03:09

ojhawkins


People also ask

What does chars () do in Java?

The chars() method is an instance method of the String class. It returns an IntStream that consists of the code point values of the characters in the given string. This method was added to the String class in Java 9.

How do I convert a char array to a string in Java?

The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);

How do you iterate through a set of elements?

Iterating over Set using IteratorObtain the iterator by calling the iterator() method. You can use while or for loop along with hasNext(), which returns true if there are more elements in the Set. Call the next() method to obtain the next elements from Set.


2 Answers

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.

like image 56
mvp Avatar answered Sep 28 '22 09:09

mvp


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;
}
like image 40
Tay Wee Wen Avatar answered Sep 28 '22 10:09

Tay Wee Wen