首页 > 解决方案 > 如何为字符串中的每个字母加 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;
    }
}

标签: ccs50

解决方案


你的问题似乎是:

我试图访问字符串中的每个字符并在打印出文本之前添加 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

推荐阅读