如何将字符串中的每个字母加 1 并打印?
How to add 1 to each letter in a string and print?
我正在尝试访问字符串中的每个字符并在打印出文本之前将其加 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;
}
}
您的问题似乎是:
am trying to access each character in a string and add 1 to it before printing out the text
这可以通过许多不同的方式来完成 - 这里是一个例子:
#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
我正在尝试访问字符串中的每个字符并在打印出文本之前将其加 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;
}
}
您的问题似乎是:
am trying to access each character in a string and add 1 to it before printing out the text
这可以通过许多不同的方式来完成 - 这里是一个例子:
#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