user3370335
user3370335

Reputation: 43

show the character of string, that user entered. C language

I'd like to ask if it's possible to do something like this: For example I have a string B with text and I wrote a code like this:

puts("Enter the number of character in string B:");

gets(number);

I would like that a program would print a character that user has entered. For example

char B[] = {"Shop"};

user entered 4 and computer prints p character. I think this should look like:

char b[number];

printf("%s", b); 

But it doesn't work. I hope that you will understand what I want to do. Sorry, for my English. Still learning.

Upvotes: 0

Views: 107

Answers (2)

Joe
Joe

Reputation: 1432

Try this:

if ((number <= strlen(B)) && (number >= 1))
    printf("%c", B[number - 1]);
else
    printf("Entered number: %d : is out of range\n", number);

Upvotes: 1

ayheber
ayheber

Reputation: 267

Regard to Joe`s answer:

Do not forget to check negative value:

    if (number <= strlen(B) && unmber>=0)
        printf("%c", B[number - 1]);
    else
        printf("Entered number: %d : is out of range\n", number);

Upvotes: 2

Related Questions