简体   繁体   中英

about printing a single character in an array without using for loop in c language

Recived blank screen output in c compiler when i used this simple code

what i need is to print a single specified character in array (without any type loop)

#include <stdio.h>
int main(void)
{
  int str[10] = {'h','e','l','l','o'};


  printf("\n%s", str[1]); //hoping to print e
  
  return 0;
}

sharing an article or something about it very appreciated

According to the documentation for the function printf , the %s format specifier is for printing a string. If you want to print a single character, you should use the %c format specifier instead:

#include <stdio.h>

int main(void)
{
    int str[10] = {'h','e','l','l','o'};

    printf( "%c\n", str[1] ); //hoping to print e
  
    return 0;
}

This program has the following output:

e

It is also worth nothing that it is normal to use the data type char instead of int , when dealing with integers representing characters:

char str[10] = {'h','e','l','l','o'};

Since we are now using char instead of int , we can also initialize the array from a string literal, which is simpler to type:

char str[10] = "hello";

Both declarations define an array of exactly 10 char elements, with the last 5 elements initialized to 0 , ie a null character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM