简体   繁体   中英

alphabet increment in c programming

I'm trying to make a program that can get a char from the user and display the next letter in the alphabet. So if you entered 'a' it would print 'b' I'm new to C and I'm not quite sure how to do it. This is what I have so far:

#include <stdio.h>

int main (){
    char firstLetter [2],  secondLetter [2];
    printf ("Type in a single letter:");
    scanf ("%s", &firstLetter);
    secondLetter = (int)firstLetter++
    printf ("The letter after %s is %s",firstLetter, secondLetter );
    return 0;
}

I tried to have letter temporarily be an integer so that I could increase it by one but it didn't work. Any ideas?

few problems I've noticed in your code.

  • firstLetter[2] : why declare an array of characters if you want the input to be a 'single letter'?
  • scanf( "%s", &firstLetter ) : why read a string if you expect the input to be a char?
  • you need to check your input

here is my solution for your problem

#include <stdio.h>
#include <ctype.h>

int main()
{
    char firstLetter;
    char secondLetter;

    printf( "Type in a single letter: " );
    firstLetter = getc( stdin );
    if ( isalpha(firstLetter) && tolower(firstLetter) != 'z' ) {
        secondLetter = firstLetter + 1;
        printf( "The letter after %c is %c\n", firstLetter, secondLetter );
    } else { 
        printf( "Invalid letter\n" );
    }

    return 0;
}

Simple code

#include <stdio.h>
#include<ctypes.h>

int main() {
int ch = -1 ;

printf("\n Enter char >>> ");
scanf("%d", &ch);

if(isalpha(ch++)){
    printf("\n Next character is %c.",ch);
}else{
    printf("\n Ooops !!! : Either goes out of range or not valid character");
}

return 0;
}

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