I want to make a program that takes letters and uses a Caesar encryption to shift them from a up 1 value to b. It must use a string in order to do this.
My problem is my program will not take the user's input into the string. (I attempted to put guy[10] in the scanf, but this only caused the program to crash-- so I willingly put the incorrect guy there so the program may compile).
#include <stdio.h>
int main(){
int i=0; //setting the individual slot number for the array-- later used in the while loop
char guy[10];
printf("Enter Plain Text:");
scanf("%s",&guy); //takes user's input-- such as "abc" and puts it into its respective slot in the array guy[10] r-right?
while (guy[10] != '\0'){ //while loop that runs until it reaches the end of the string
if ((guy[i]) >= 'A' && (guy[i]<= 'Z')){ //moves capital letter values up 1
guy[i]=guy[i]++; //makes the current "slot" number go up 1 value. Example: a = 97 + 1 -> b = 98
}
if ((guy[i]) >= 'a' && (guy[i]) <= 'z'){// moves lower case letter values up 1
guy[i]=guy[i]++;
}
i++; //moves the array's interval up to the next "slot"
}
printf("Encrypted text is: %s",guy);
}
Your first issue is this line:
scanf("%s",&guy);
as guy
is an array so we don't need to get a pointer to it, it's name is treated as a pointer in this context. Simply do:
(void) scanf("%s", guy);
Your second issue is this line:
while (guy[10] != '\0')
as WhozCraig noted int his comment -- this should use index i
, not 10
The third issue is that this statement makes little sense:
guy[i]=guy[i]++;
Reasonable alternatives include:
guy[i] = guy[i] + 1;
guy[i]++;
guy[i] += 1;
The fourth issue is you've not dealt with wrap-around. E.g. what does 'Z' map to in your code? It looks like it will come out as "[" instead of "A".
The fifth issue is that scanf()
can overflow the array guy
as it's input size is unlimited. For guy[10]
, we need to do something like:
scanf("%9s", guy);
To limit the input to nine characters with room for the final '\0'. Using fgets()
would be a better choice in this situation as it's safer and we don't need the parsing power of scanf()
:
fgets(guy, 10, stdin);
Here's a rework that addresses these five issues:
#include <stdio.h>
int main() {
char text[10];
printf("Enter Plain Text: ");
(void) fgets(text, 10, stdin); // takes user's input -- such as "abc" and put it into its respective slots in the array
int i = 0; // slot index for the array
while (text[i] != '\0') { // loop until reach end of string
if (text[i] >= 'A' && text[i] <= 'Z') { // move capital letter values up 1
// make the letter go up 1 modulo 26. Example: A = 65 + 1 -> B = 66; Z = 90 + 1 -> A = 65
text[i] = ((text[i] - 'A' + 1) % ('Z' - 'A' + 1)) + 'A';
} else if (text[i] >= 'a' && text[i] <= 'z') { // move lower case letter values up 1
text[i] = ((text[i] - 'a' + 1) % ('z' - 'a' + 1)) + 'a';
}
i++; // move the array's index up to the next "slot"
}
printf("Encrypted text is: %s\n", text);
}