0

So I'm banging my head because my program doesn't print the spaces. For example, if the key is 1 and enter: a b c, it should output: b c d, but right now it's just printing "b" and doesn't recognize the space. I did also see this post: Pset 2 Caesar doesnt output spaces correctly and more :(

but still having issues. Any ideas?

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

#define MAX_STRING 50

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);

  char cipherLetter[2] = ""; // sets all chars to '\0'

  // Define variable for input
  char text[MAX_STRING];
  // Get user input

  printf("\nplaintext: ");
  scanf("%s", text);


  // loop through each character in the word
  for (int i = 0; i < strlen(text); i++) {
    // check if character is an uppercase letter
    if (isalpha(text[i]) && isupper(text[i])) {
      // get the new ascii value w/ formula c = (plaintext + key) % 26, and add the char to an array
      cipherLetter[0] = (text[i] + key2 - 65) % 26 + 65;
      // print each character to screen
      printf("%c", cipherLetter[0]);
    }
    // check if character is a lowercase letter
    else if(isalpha(text[i]) && islower(text[i])) {
       // get the new ascii value w/ formula c = (plaintext + key) % 26, and add the char to an array
      cipherLetter[0] = (text[i] + key2 - 97) % 26 + 97;
      // print each character to screen
      printf("%c", cipherLetter[0]);
    }
    else {
      // get the character
      cipherLetter[0] = text[i];
      // print each character to screen
      printf("%c", cipherLetter[0]);
    }



  }

}

1 Answer 1

3

Looking at your code, I'm guessing that you aren't following the current course (2019 CS50x). You are missing many concepts that are required.

Saying that, your issue is that scanf as you've used it will stop when it hits a space, so if you enter "a b c" , text will be "a" and the rest is ignored.

I'd suggest you use get_string from the CS50 library per the spec, especially if plan to submit your code:

2019 CS50x Caesar problem

1
  • hi, thank you. I marked your answer as the correct one. Appreciate the help.
    – wolfbagel
    Commented Feb 28, 2019 at 15:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .