【发布时间】:2014-06-26 18:21:42
【问题描述】:
我正在尝试通过凯撒加密来加密字符串,但它仅适用于一个单词(字符之间没有空格)。我想加密整个句子。我在这里读过关于通过gets() 或fgets() 将键盘中的空格转换为字符串,但我无法使其正常工作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
printf("Enter the shift: ");
int shift,index,length;
scanf("%d", &shift);
printf("Enter the string to encrypt: " );
char string[1000];
//gets(string);
scanf("%s",string);
//fgets(string,1000,stdin);
char encrypted[strlen(string) + 1];
for(index = 0, length = strlen(string); index < length; index++ ){
if (string[index]!=' ')
encrypted[index] = 'A' + (string[index] -'A' + shift) % 26;
else
encrypted[index]=' ';
}
encrypted[ strlen(string)] = '\0';
printf("%s\n", encrypted);
return (EXIT_SUCCESS);
}
【问题讨论】:
-
您的尝试如何“不起作用”?您预计会发生什么,实际会发生什么?
-
用循环或对
fgets的调用替换scanf——使用man fgets查找文档 -
请忘记你听说过
gets:安全使用它几乎是不可能的。 -
永远不要使用
gets(),即使在练习程序中也是如此。 It is a horrible security hole. -
试试
scanf(" %999[^\n]", string);
标签: c string scanf fgets spaces