c - 如何为字符串中的每个字母加 1 并打印?
问题描述
我正在尝试访问字符串中的每个字符并在打印出文本之前为其添加 1。例如。我的代码将提示用户输入文本,即。你好,它应该打印该文本加上1个字符(即当输入为“hello”时输出“ifmmp”)。从下面的代码中,我尝试使用 while 循环而不是 for 循环来执行此操作,但是我遇到了一些问题,并且似乎没有打印响应。非常感谢任何帮助。
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// If
if (argc == 2 && (atoi(argv[1]) > 0))
for(int i = 0, len = strlen(argv[1]); i < len; i++)
{
char n = argv[1][i];
int digit = isdigit(n);
if (!digit)
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
string plain = get_string("plaintext: ");
int k = 0;
int len_plain = strlen(plain);
while (len_plain > k)
k++;
char cipher = plain[k];
{
printf("%c\n", cipher);
}
}
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
}
解决方案
你的问题似乎是:
我试图访问字符串中的每个字符并在打印出文本之前添加 1
这可以通过许多不同的方式来完成 - 这是一个例子:
#include <stdio.h>
int main(void) {
char str[10] = "hello";
int i = 0;
while(str[i])
{
++str[i]; // Add 1
++i;
}
printf("%s\n", str);
return 0;
}
输出:
ifmmp
推荐阅读
- sql - Powershell foreach SQL Server 查询随机整理数据集
- reactjs - 如何使用 paymentIntent 和 confirmCardPayment 集成条带
- excel - For 循环和逐步着色单元格
- macos - 如何在 Mac 上卸载旧版 Unity
- javascript - 如何在 ReactJS 中的两个类和组件之间传递数据?
- javascript - 除了错误和警告之外,还有其他方法可以构建 create-react-app 项目吗?
- java - 如何正确地将图像下载到我的相机胶卷?
- amazon-web-services - 从 ES 中删除字段
- python-3.x - 如何将 txt 文件中的数据读入行和列以进行平均计算 Python
- javascript - 有没有一种简单的方法可以在 React Native 中创建事件和侦听器