JBo
JBo

Reputation: 89

Caesar cipher printing out numbers instead of decrypted Text? in C

So I have this caesar cipher program, however when I run it it only prints out numbers instead of the decrypted text. Anyone know what I am missing? I believe there might be something wrong in the bool solved function.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "rotUtils.h"

bool solved( char decodearr[], char dictarr[][30], int size1, int size2){

    char* compared;
    bool result = false;

    for(int j = 0; j < size2; j++){

    compared = strstr( decodearr, dictarr[j]);

    }
    if( compared != '\0'){

     result = true;

         }
    return result;

}

int decode( char codearr[], char dictarr[][30], int size1, int size2)
    {
    bool solution = false;
    int key = -50;
    char decodearr[10000];
    while(solution == false && key < 51)
    {
     for( int i = 0; i < size1; i++)
        {
        if(!isspace(codearr[i]))
         {
          decodearr[i] = rotate(codearr[i], key);
          }
        else
          decodearr[i] = codearr[i];


    }

    solution = solved( decodearr, dictarr, size1, size2);
    if( solution == false)
     {
      key++;
      }
    }
  for( int j = 0; j < size1; j++)
    {
    codearr[j] = decodearr[j];
    }
  return key;
}

    int main( int argc, char* argv[])
    {
    char* file = argv[1];
    char* dictionary = argv[2];
    char code[10000];
    char dict[30000][30];
    FILE* codeFile;
    codeFile = fopen(file, "r");
    int i = 0;
    int j = 0;
    int key;
    FILE* dictFile;
    dictFile = fopen(dictionary, "r");

    while(!feof(codeFile))
    {
    code[i] = fgetc(codeFile);
    i++;
    }

    code[ i + 1] = '\0';
    fclose(codeFile);

    while(!feof(dictFile))
    {
    fscanf(dictFile, "%s", dict[j]);
    j++;
    }

    key = decode(code, dict, i, j);
    fclose(dictFile);

        for(int k = 0; k < i; k++)
        {
        printf("%d", code[k]);
        }

    printf( "\nThe key is: %d\n", key);

    return 0;
}

Upvotes: 0

Views: 87

Answers (3)

acenturyandabit
acenturyandabit

Reputation: 1418

Just use "%c" instead of "%d" in your code when you want to print code[k]. Good luck!

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44308

You only ever print numbers

 printf("%d", code[k]);

perhaps try

printf("%c", code[k]);

which prints the character that number represents.

Upvotes: 1

autistic
autistic

Reputation: 15642

printf("%d", code[k]); means "print out the decimal digits that represent the integer code[k]".

If you want "print out the character that represents the integer code[k], then you'd want the %c format specifier instead: printf("%c", code[k]);

Upvotes: 2

Related Questions