0

I'm trying to implement a substitution cipher but my output is printing on the following lines rather than on the same line. For example, if my key is VCHPRZGJNTLSKFBDQWAXEUYMOI, then HELLO should output JRSSB, which my code does but it looks like this (I've attached a screenshot of the output as well): JR \n S \n SB

printf("ciphertext: ");
for (int i=0; i<strlen(plain); i++)
{

    if (arr[i]>90 || arr[i]<65)
    {
        printf("%c", arr[i]);
    }   

    for (int j=0; j<strlen(key); j++)
    {
        if ((arr[i]==j) && (lower == true))
        {
            printf("%c", key[j]+32);
        }
        else if (arr[i]==j)
        {
            printf("%c", key[j]);
        }
    }

}

enter image description here

Imanpal Singh
  • 1,105
  • 1
  • 12
  • 22
jackli8
  • 9
  • 1
  • 3
    Since the ASCII value for the `'\n'` character is `10` (`0xa`), your condition allows it to be printed -- `arr[i]<65`. – David C. Rankin Jun 15 '20 at 05:33
  • Where does the variable `lower` get initialized? – Mawg says reinstate Monica Jun 15 '20 at 05:34
  • 2
    Kindly provide the entire code. What is plain and arr? – Deepak Tatyaji Ahire Jun 15 '20 at 05:34
  • @DavidC.Rankin That was precisely the problem, I added (arr[i]>31) and it works perfectly! Thank you for your help. – jackli8 Jun 15 '20 at 05:38
  • 1
    Use `isupper()` from the standard library instead, note that you need to include ``, `tolower()`, `toupper()` and don't rely on ASCII value, it's not always the case. https://stackoverflow.com/a/13827351/13158151 – Saadi Toumi Fouad Jun 15 '20 at 05:38
  • 2
    Welcome to programming... We've all been there. Learning [**How to debug small programs**](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) greatly shortens the time it takes to find issues like this. It's really all about developing a systematic way to step through your program to find where the bug are hidden. Developing good habits working with 50 lines of code will make things much easier when dealing with 50,000 lines of code `:)` – David C. Rankin Jun 15 '20 at 05:41
  • avoid those kinds of magic numbers. `arr[i] < 'A'` and `arr[i] > '0'` are much more readable – phuclv Jun 15 '20 at 08:06

0 Answers0