user8314628
user8314628

Reputation: 2042

How to get char from string by index in c language?

#include <stdio.h>

int main() {
    char str[11];
    int num;
    scanf("%s %i", &str, &num);
    printf("You typed %s and %i\n", str, num);
    if (num == 0)
    {
        printf (str);
    }
    else
    {
        printf (str[num]);
    }
    return 0;
}

The input is a phone number and a digit. If the digit is not 0, then print number[digit].

It the last second line, I tried both str[num] and &str[num]. The first case will cause Segmentation fault (core dumped). The second one will return a string but not a char.

6479378812 1                                                                                                                                                                       
You typed 6479378812 and 1                                                                                                                                                         
479378812

But what I want is the second digit, which is 4. How can I fix it?

Upvotes: 0

Views: 4140

Answers (2)

Norbert Incze
Norbert Incze

Reputation: 351

You have to specify what do you want to print with the printf function.

printf("%c", str[num]);

With %c you tell to the function that you want to print a character. If you want to print a whole string, you shall use %s.

By the way, you shall always specify the formatting string, because it is unsafe if you do not specify it. https://en.wikipedia.org/wiki/Uncontrolled_format_string

Upvotes: 1

Ass3mbler
Ass3mbler

Reputation: 3935

You need to specify the formatting string for your printfs. The first needs a string format "%s", the second a single character "%c". You can find all the details about the format used in the formatting string of printf() here.

#include <stdio.h>

int main() {
    char str[11];
    int num;
    scanf("%s %i", &str, &num);
    printf("You typed %s and %i\n", str, num);
    if (num == 0)
    {
        printf ("%s", str);
    }
    else
    {
        printf ("%c", str[num]);
    }
    return 0;
}

Upvotes: 3

Related Questions