Reputation: 11
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?
Upvotes: 1
Views: 13393
Reputation: 33
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;
}
Upvotes: 0
Reputation: 974
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?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;
}
Upvotes: 7