Thread: How to concatenate in C?

  1. #1
    Registered User
    Join Date
    Feb 2019
    Posts
    5

    How to concatenate in C?

    I think I'm close but something is a little off with my algorithm. I'm writing a Caesar encryption and when I type: HELLO, it should return IFMMP but it's returning this:

    How to concatenate in C?-screen-shot-2019-02-22-4-00-25-pm-png

    I'm taking a CS class online, just auditing the course. We haven't learned about pointers quite yet, so not sure if that's the problem?

    Here's my code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char *argv[]) {
      // User enters parameters for the argument
      // Get the argument for argv[1], read in the key in that positon of the argument
      char *key = argv[1];
      // convert keyt to an integer
      int key2 = atoi(key);
    
      int cipherValue;
      char cipherLetter;
      char str[30];
    
      // Define variable for input
      char text[30];
      // Get user input
    
      printf("\nplaintext: ");
      scanf("%s", text);
      // get length of the plaintext
      long textLen = strlen(text);
    
      // create lookup array, for each lowercase letter in alphabet (a - z), starting from index 0 to 25
      char lettersLower[26];
      int index_l = 0;
      for (int i = 97; i < 123; i++) {
        // implicitly convert int to char
        char c = i;
        // add char to lookup table index
        lettersLower[index_l] = c;
        // increment the index counter
        index_l++;
    
      }
    
      // create lookup array, for each uppercase letter in alphabet (A - Z), starting from index 0 to 25
      char lettersUpper[26];
      int index_u = 0;
      for (int i = 65; i < 91; i++) {
        // implicitly convert int to char
        char c = i;
        // add char to lookup table index
        lettersUpper[index_u] = c;
        // increment the index counter
        index_u++;
    
      }
    
      // for each letter in the plaintext word, get the index of the letter from the array and add 1, then take the modulo of 26 to get the ciphertext index
      for (int i = 0; i < textLen; i++) {
        // get each letter in the text
        char plainLetter = text[i];
        int asciiValue = plainLetter;
        // lookup the value in lowercase letters array, if it's a lowercase letter then...
        if (asciiValue > 96 && asciiValue < 123) {
          for (int j = 0; j < 26; j++) {
              // if the value is found then
            if (plainLetter == lettersLower[j]) {
              // add the value(j) plus 1 % 26, to get the ciphertext value
              cipherValue = (j + key2) % 26;
              // lookup new value in letter array
              for (int k = 0; k < 26; k++) {
                // if the ciphervalue equals the key's value then print out the new letter
                if (cipherValue == k) {
                  // implicitly convert int to char value
                  cipherLetter = lettersLower[k];
                  //printf("this is concat letter: %c\n", cipherLetter);
                  // concatenate each letter
                  strcat(str, &cipherLetter);
    
    
                }
              }
            }
          }
        }
        //lookup the value in uppercase letters array, if it's an uppercase letter then... 
        else if (asciiValue > 64 && asciiValue < 91) {
          // search the lookup table
          for (int l = 0; l < 26; l++) {
            // if the uppercase value is found
            if (plainLetter == lettersUpper[l]) {
              // add the value(l) plus 1 % 26, to get the ciphertext value
              cipherValue = (l + key2) % 26;
    
              // lookup new value in letter array
              for (int m = 0; m < 26; m++){
                // if the ciphervalue equals the key's value then print out the new letter
                if (cipherValue == m) {
                  // implicitly convert int to char value
                  cipherLetter = lettersUpper[m];
                  // concatenate each letter
                  strcat(str, &cipherLetter);
                  
                }
              }
              
            }
    
          }
        }
      
    
    
      }
    
      
        // print out concatenated string
        printf("ciphertext: %s\n", str);
    
    
    }
    

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Congratulations, I did not think anyone could make the "Caesar encryption" program too complex for me to follow; but, you succeeded.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    Your main problem is that you are setting a single char to the character you want and then passing the address of that char to strcat, which treats the char as a string. But a real string must have a '\0' character to indicate where it ends. So to do what you want, you need an array of 2 chars with the second one being '\0'.
    Code:
    // At top of program:
    char cipherLetter[2] = "";  // sets all chars to '\0'
     
    ...
     
    cipherLetter[0] = ch;
    strcat(str, cipherLetter);
    However, the whole thing can be done more simply.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    #define MAX_STRING 200
     
    int main(int argc, char **argv) {
        if (argc != 2) {
            fprintf(stderr, "Usage: caesar <OFFSET>\n");
            exit(EXIT_FAILURE);
        }
     
        int offset = atoi(argv[1]);
     
        if (offset < 0 || offset > 25) {
            fprintf(stderr, "OFFSET must be from 0 to 25.\n");
            exit(EXIT_FAILURE);
        }
     
        char plain[MAX_STRING];
        printf("Plaintext: ");
         
        // fgets allows reading a whole sentence
        // but it leaves the newline char ('\n') at the end of the string
        fgets(plain, sizeof plain, stdin);
     
        char cipher[MAX_STRING];
        int i = 0;
        for ( ; plain[i] && plain[i] != '\n'; ++i) {
            char ch = plain[i];
            if (ch >= 'a' && ch <= 'z')       // or if (islower(ch))
                cipher[i] = (ch - 'a' + offset) % 26 + 'a';
            else if (ch >= 'A' && ch <= 'Z')  // or if (isupper(ch))
                cipher[i] = (ch - 'A' + offset) % 26 + 'A';
            else
                cipher[i] = ch;
        }
     
        // It's crucial to zero-terminate the string.
        cipher[i] = '\0';
     
        printf("%s\n", cipher);
     
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    5
    Thank you John! Your code is beautiful! Hope to write code like you one day soon!
    Last edited by geekchick; 02-22-2019 at 06:55 PM.

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    5
    Quote Originally Posted by stahta01 View Post
    Congratulations, I did not think anyone could make the "Caesar encryption" program too complex for me to follow; but, you succeeded.

    Tim S.
    I've only been coding for 2 months. I'm sure it takes a lot longer to write more concise code. Hope to get there soon.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I can't concatenate a string
    By qqsszz in forum C Programming
    Replies: 9
    Last Post: 06-29-2018, 03:55 PM
  2. trying to concatenate: help!
    By django in forum C Programming
    Replies: 10
    Last Post: 08-07-2011, 06:17 PM
  3. concatenate
    By violatro in forum C Programming
    Replies: 16
    Last Post: 06-04-2010, 09:22 AM
  4. Concatenate string and int
    By millsy5 in forum C Programming
    Replies: 1
    Last Post: 01-28-2010, 04:43 AM
  5. concatenate
    By port in forum C Programming
    Replies: 1
    Last Post: 11-25-2002, 09:53 PM

Tags for this Thread