I'm writing to understand as much as I can of the following program that I tried to compute, because I thought it had some possible application for everyday life.
The program goes like this (it's a cypher):
#include <stdio.h>
void cifrario(int k) {
char b, d;
scanf("%c", &d);
d = getchar();
putchar(d);
scanf("%c", &b);
b = getchar();
while (b != d) {
if (('A' <= b && b <= 'Z') || ('a' <= b && b <= 'z')) {
b = b + k;
printf("%c", b);
scanf("%c", &b);
b = getchar();
} else
printf("%c", b);
}
}
int main() {
int h;
scanf("%d", &h);
cifrario(h);
return 0;
}
As you can see, I'm trying to shift the alphabet of a certain constant given in input.
The things I'm not quite understanding and I'm not quite aware of, are why the program should not function without a scanf
or getchar
, and both are necessary on the same value, let's say here:
scanf("%c", &d);
d = getchar();
I thought the two were totally equivalent; in fact searching on the internet I found this as far as concerns getchar
:
This function returns the character read as an
unsigned char
cast to anint
orEOF
on end of file or error.
That's what I expected scanf()
did.
I have found that:
if I put all the character without spaces I'm getting (I think) just a shift of the same character for double letter instead of two.
the
else
in thewhile
doesn't work as expected because as soon I put a different character from the alphabetic ones and see the outcome the output fail in an infinite string of that character.