0

我需要读入用户输入和用户凯撒密码来加密它。但是在阅读用户输入时我遇到了以下问题,如果我输入例如,我的程序不会终止:“ ./caesar 3 I'm”问题似乎是字符'。该程序适用于其他输入。

/**
 *
 * 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;
} 
4

1 回答 1

5

Shell 将 解释'为字符串的开头。所以你需要逃避它:

./凯撒 3 我是

或将参数括在双引号中:

./caesar 3 “我是”

请注意,这与您的程序无关。只有命令行外壳处理这个问题。

于 2012-11-26T09:17:09.650 回答