I'm trying to create a cipher that eventually will read an entire .dat file then re-write it encrypted and as of now I am using code blocks. Right now I’m just working on being able to do it one word at a time, but I get a really big error when I try to decrypt the word. The word is decrypted and printed then my computer starts to make a long beep sound and prints lines and lines of jargon. The program works fine until the end when I try to decrypt the word. I’ve only started programming about 4 months ago, so any help/advice will be greatly appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


//function prototype

void encrypt (char [], int);
void decrypt (char [], int);

int main (void)

{

char myString[21] = {0};
int iSelection = 0;
int iRand;

srand(time(NULL));

iRand = (rand() % 4) + 1; //random#, 1-4


    printf("\n\n1   Encrypt Text");
    printf("\n2   Decrypt Cipher Text");
    printf("\n3   Generate New Key");
    printf("\n4   Quit");
    printf("\n\n\nSelection a Cryptography Option: ");
     scanf("%d", &iSelection);

    switch (iSelection){

    case 1:
       printf("\nEnter one word to encrypt: ");
        scanf("%s", myString);
        encrypt(myString, iRand);
        break;
    case 2:
       printf("\nEnter cipher text to decrypt: ");
        scanf("%s", myString);
        decrypt(myString, iRand);
        break;
    case 3:
       iRand = (rand() % 4) + 1; //random#, 1-4
       printf("\nNew Key Generated\n");
       break;
    case 4:
       printf ("FAILED");
    } //end switch

return 0;
}//end main

//functions

void encrypt(char sMessage[], int random){

    int x = 0;

//encrypt the message by shifting characters

    while(sMessage[x]){
        sMessage[x] += random;
        x++;
    }//end loop

    x = 0;
    printf("\nEncrypted Message is: ");

//print the encrypted message

    while(sMessage[x]){

        printf("%c", sMessage[x]);
        x++;
    }//end loop
}//end encrypt function

void decrypt(char sMessage[], int random){

    int x = 0;
    x = 0;

//decrypt the message by shifting the letters

    while(sMessage[x]){
        sMessage[x] = sMessage[x] - random;
        x++;
    }//end loop

    x = 0;
    printf ("\nDecrypted Message is: ");

//print the decrypted message

    while("sMessage[x]"){
        printf("%c", sMessage[x]);
        x++;
    }//end loop
}//end decrypt funcion

I attached a file showing what the problem is. This is my first post so I hope it worked..

Recommended Answers

All 2 Replies

while("sMessage[x]"){

Why quotes?! ;)
It's a loop forever: while (pointer to string literal != 0). It never is null...

commented: good catch +8
commented: Indeed +29

Thanks! Your are my hero lol

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.