C:用户输入包含“'”字符的字符串

时间:2012-11-26 09:13:37

标签: c encryption char caesar-cipher cs50

我需要读取用户输入和用户Caesar cypher来加密它。但是在读取用户输入时我遇到了以下问题,如果我输入例如:./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;
} 

1 个答案:

答案 0 :(得分:5)

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

./caesar 3 I\'m

或用双引号括起参数:

./caesar 3 "I'm"

请注意,这与您的程序无关。它只是处理此问题的命令行shell。