Obwohl Dac Saunders schon eine nette Erklärung und eine gute Skizze gegeben hat, denke ich, dass ein zweites, etwas anderes Beispiel hilfreich sein könnte.
// for printf() and puts()
#include <stdio.h>
// for exit() and the macro EXIT_SUCCESS
#include <stdlib.h>
// for tolower() and isupper()
#include <ctype.h>
// All calculations assume ASCII encoding!
int main()
{
char letter;
puts("Alphabet Facts!");
puts("^^^^^^^^^^^^^^^");
// You want an upper case letter as the input, so check for it
do {
printf("\nPlease input an uppercase letter: ");
letter = getc(stdin);
// swallow new-line(s)
getc(stdin);
#ifdef _WIN32
getc(stdin);
#endif
} while (!isupper(letter));
printf("\nSome interesting facts:\n\n");
printf(" 1) The lowercase version of the letter is '%c'.\n\n", tolower(letter));
if (letter == 'A') {
// or print 'Z' if you want it to mimic a circle
printf(" 2) No letter comes before '%c' in the alphabet.\n", letter);
} else {
printf(" 2) The letter '%c' comes before '%c' in the alphabet.\n\n", letter - 1, letter);
}
if (letter == 'Z') {
// or print 'A' if you want it to mimic a circle
printf(" 3) No letter comes after '%c' in the alphabet.\n\n", letter);
} else {
printf(" 3) The letter '%c' comes after '%c' in the alphabet.\n\n", letter + 1, letter);
}
// 'A' is at position 64 in the table of the ASCII encoding but we don't need to
// look it up, we can use the letter itself because a 'char' is a number, too.
// The ASCII table is zero based--we need to subtract unity from 'A' or add unity
// after the subtraction of 'A'.
printf(" 4) %c is letter number %d in the alphabet!\n\n", letter, letter - ('A' - 1));
// return the special number to the OS that tells it that no error occured.
exit(EXIT_SUCCESS);
}
Sie können Arithmetik für Char-Variablen ausführen. Zum Beispiel gibt 'H' - 1 Ihnen 'G' – samgak
Wie bei allen anderen Computern werden Buchstaben mit Zahlen dargestellt, was bedeutet, dass Sie diese Zahlen addieren und subtrahieren können. Der älteste (ich denke) und grundlegendste Standard der Nummer <--> Buchstaben Mapping ist ASCII. Eine schnelle Google-Suche wird Ihnen die ASCII-Codes mitteilen. Sieh dir das auch an: https://unmad.in/conv_guide/ch01.html – yano
@samgak Es kommt auf das jeweilige Alphabet an. Eine allgemeinere Lösung erfordert eine explizite Sequenz (z. B. eine Zeichenfolge) für das relevante Alphabet. Und natürlich sind einige Buchstaben, die im Schriftsystem für eine Sprache verwendet werden, nicht im Alphabet der Sprache (und das gilt für Englisch). –