[英]C: User input String including “ ' ”-character
I need to read in the user input and the user Caesar cypher to encrypt it. 我需要读入用户输入和用户Caesar密码以对其进行加密。 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 '
. 但是在读取用户输入时,我遇到以下问题,例如,如果输入以下内容,则程序不会终止:“
./caesar 3 I'm
”问题似乎是字符'
。 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;
}
The shell interprets the '
as the start of a string. shell将
'
解释为字符串的开头。 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.
只是命令行外壳程序可以处理此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.