siebenschlaefer siebenschlaefer - 3 months ago 9
C Question

C: User input String including " ' "-character

i got following question. I need to read in the user input and user caeser cypher to encrypt it. But while reading in the user input i got following problem, that my program does not terminate if i enter for example: "./caesar 3 I'm"
The problem seems to be the character ' . The program works for other input.

/**
*
* caesar.c
*
* The program caesar encrypts a String entered by the user
* using the caesar cipher technique. The user has to enter
* a key as additional command line argument. After that the
* user is asked to enter the String he wants to be encrypted.
*
* Usage: ./caesar key [char]
*
*/

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

int caesarCipher(char original, int key);

int main(int argc, string argv[])
{
if (argc > 1)
{
int key = atoi(argv[1]);

for (int i = 2; i < argc; i++)
{
for (int j = 0; j < strlen(argv[i]); j++)
{
argv[i][j] = caesarCipher(argv[i][j], key);
}
}

for (int i = 2; i < argc; i++)
{
printf("%s", argv[i]);
}

return 0;
}
else
{
printf("The number of command arguments is wrong! \n");

return 1;
}
}

int caesarCipher(char original, int key)
{
char result = original;

if (islower(original))
{
result = (original - 97 + key) % 26 + 97;
}
else if (isupper(original))
{
result = (original - 65 + key) % 26 + 65;
}

return result;
}

Answer

The shell interprets the ' as the start of a string. So you need to either escape it:

./caesar 3 I\'m

or enclose the argument in double quotes:

./caesar 3 "I'm"

Note that this has nothing to do with your program. It's only the command-line shell that deals with this.