#include <stdio.h>
int main()
#include <stdio.h>
int main()
{
char msg[31] = {'\0'};
char encrypted[31] = {'\0'};
int key;
printf("Please enter a message under 30 characters: ");
fgets(msg, 31, stdin);
printf("Please enter an encryption key: ");
scanf("%d", &key);
int i = 0;
while (msg[i] && ('a' <= msg[i] <= 'z' || 'A' < msg[i] < 'Z'))
{
encrypted[i] = (msg[i] + key);
i++;
}
printf("%s\n", msg);
printf("%d\n", key);
printf("%s\n", encrypted);
}
好的,我已经得到了增加字符的代码,但我不知道如何让它忽略特殊字符和空格。另外,我如何使用 %
循环回到 'a'
和 'A'
?
谢谢。
最佳答案
您只需要一个简单的
for
循环:for (int i = 0; i < 31; i++) { // operate on msg[i] }
如果您不知道字符串的开头长度,您可能更喜欢检测空终止符的
while
循环:int i = 0; while (msg[i]) { // operate on msg[i] i++; }
您的
fgets
和scanf
可能没问题,但就个人而言,我会在读取输入时保持一致,而fgets
全部。然后您可以sscanf
稍后获取key
。
关于c - 我如何循环遍历字符串中的每个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14572423/