Defcon97 Defcon97 - 9 months ago 38
C Question

Issue with string printing

I was trying to create a program to ecrypt string with Ceasar's cypher, if you are not familiar with the Ceasar cypher it is a really simple encryption method, it operates using the input string and a number "n" that can be chosen by the user and then just shifts the whole alphabet n-times. for axample if n=1 then all the A's become B's and so on. this program should have an input string that should be read by the program via keyboard input and an n number that has to be chosen by the user as well; and should return a string where the first character represents the first character uf the unencrypted string and then the following characters should be the encypted version of the input string, encrypted with Ceasar's cypher using the n number chosen by the user. for the sake of brevity I have not included in this post the part of the code where the program scans the n value and adjusts it (it obviously has to be smaller than 26), and I have canceled as well the part of the program that turned the input string in upper case.

int main() {
int i, n;
char uncod[200] = {0};
char cod[200] = {0};
printf("insert the string to encript:");
scanf("%[0-9a-zA-ZSPACE]", uncod);
cod[0] = (char)uncod[0];
for(i == 1; i < 200; i++) {
sprintf(cod, "%d + n", uncod[i]);
if (cod[i] > 90) {
cod[i] = 64 + n;
if (cod[i] < 65) {
cod[i] = 91 + n;
printf("%s\n", cod);

This program should take the ASCII code of the unencypted string and add or subtract n to find te right character by mere assignation, it just runs through the array and assigns to every character his cyphered counter-part after having assigned to the first value of the output string the unencrypted first character of the input string. The issue is that when I go to print the output string, it'll only print the first character and ignore the rest. how to solve this?

Answer Source
  • n is not initialized anywhere.
  • Not sure what this line is supposed to do "sprintf(cod, "%d + n", uncod[i])". Why concatenating such a string to your encrypted output?
  • You would probably want to stop the loop when string is terminated (\0).