c - C 中的局部作用域
问题描述
我在C中有这样的东西:
string getCipherText(string text, int key) {
string cipherText = "";
printf("Plaintext: %s, key: %i\n", text, key);
key = key % 26;
for (int i = 0; i < strlen(text); i++) {
if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
text[i] = (int) text[i] + key;
}
cipherText += text[i];
}
return cipherText;
}
为什么我返回的密文字符串是空的?它不是 for 循环中的同一个变量吗?它是来自 EdX https://ide.cs50.io的云 IDE ,它们在cs50.h中有一个字符串类型
解决方案
假设这string
是 , 的别名char*
,cipherText += text[i];
不是连接字符串而是移动指针。
您应该像这样分配一个缓冲区并将结果存储在那里:
string getCipherText(string text, int key) {
size_t len = strlen(text):
string cipherText = malloc(len + 1);
if (cipherText == NULL) {
fputs("malloc() failed!\n", stderr);
return NULL;
}
printf("Plaintext: %s, key: %i\n", text, key);
key = key % 26;
for (int i = 0; i < len; i++) {
if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
text[i] = (int) text[i] + key;
}
cipherText[i] = text[i];
}
cipherText[len] = '\0';
return cipherText;
}
推荐阅读
- javascript - 如何使用 java 脚本更改引导卡头值?
- excel - VBA - 在列中查找最后使用的行
- javascript - 如何使用 JQuery 从自定义输入中获取 URL 参数
- android - Ionic cordova build android 卡在启动画面
- python-3.x - 详细的 if 条件 " if not hasattr(self, '__total'):"
- c - 在 C 中初始化和检查指针和其他自动变量
- jenkins - 将 Jenkins 从站安装为服务“KeyUsage 不允许数字签名”时出错
- ios - iOS UITesting 元素出现几秒钟
- mysql - 如何通过 mysql 使用 group 进行嵌套选择
- python - Python - For 循环数百万行