【问题标题】:Unable to get output even though my logic is working即使我的逻辑正常工作也无法获得输出
【发布时间】:2023-03-05 12:46:01
【问题描述】:

我用 C 创建了一个程序。该程序是一个版本替换字符串。我已经使用 printf 语句仔细分析了程序。我的程序逻辑工作正常。但是我无法添加或连接字符串。

我没有得到 encryptKey 函数的输出。这是为什么?我之前在 JS 中编程,现在正在尝试 C。

这是我的代码:-

#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>

string encryptKey(string message);

//stores the cipher word for each alphabet
//used for encryption purposes
char cipher[26];

int main(int argc, string argv[])
{

    //Exit the program if no key is added in commandline
    if(!argv[1] || argc >= 3)
    {
        printf("Incorrect or missing command line arguments!\n");
        return 1;
    }

    //checks if there are 26 characters in the decipher key
    if(strlen(argv[1]) != 26)
    {
        printf("Need 26 characters to decipher the key\n");
        return 1;
    }

    //check all the individual characters of the key
    for(int i = 0; i < 26; i++)
    {
        //check if the characters are letters only
        if(tolower(argv[1][i]) < 'a' && tolower(argv[1][i]) > 'z')
        {
            return 1;
            printf("All characters should be letters!\n");
        }

        //checks if each letter exists once

        //load the secret key to an array
        cipher[i] = argv[1][i];
    }


    //Asks user for message
    string message = get_string("plaintext:");
    string secretMessage = encryptKey(message);

    //outputs secret message
    printf("ciphertext: %s\n", secretMessage);
}

//encrypt the message
string encryptKey(string message)
{
    string output = "";

    //loop through each alphabet
    for(int i = 0; i < strlen(message); i++)
    {
        char lower = tolower(message[i]);

        if(lower >= 'a' && lower <= 'z')
        {
            //small case starts from location 97
            int tempLocation = lower - 97;


            if(isupper(message[i]))
            {
                output += toupper(cipher[tempLocation]);
            }
            else if(islower(message[i]))
            {
                output +=  tolower(cipher[tempLocation]);
            }
            else
            {
                output += message[i];
            }
        }
    }

    return output;
}

我什至试过这个来加入字符串:- strcat(输出, toupper(cipher[tempLocation]));

我收到此错误:-

error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Werror,-Wint-conversion]
                strcat(output, toupper(cipher[tempLocation]));
                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/string.h:130:70: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
                                                                     ^

【问题讨论】:

  • output += toupper(cipher[tempLocation]); 不是 string 附加在 C 中。那只是添加到指针 output
  • 我尝试使用 strcat 但我得到了上面发布的错误
  • strcat(output, toupper(cipher[tempLocation])); 失败,因为 1) cipher[tempLocation]) 不是 字符串 和 2) output 指向的空间太小。 (string output = ""; 是 1 个字节的字符)
  • 您需要在循环中为每个字符调用 toupper,确保字符串以 null 结尾,然后将其传递给 strcat。一般来说,你不能通过反复试验来编程,你必须知道你在做什么。这包括在调用之前研究你调用的每个函数。
  • 所有字符串处理问题的根源是 CS50。这是一门非常糟糕的课程,未能教授如何在 C 中正确使用字符串。我强烈建议您停止学习。

标签: c cs50


【解决方案1】:

正如 chux 所说 - 恢复莫妮卡: 字符串在 C 中的工作方式不同。

这里有一些提示:

  • 给输出一些内存:
char output[512] = { 0 };
  • 正确分配字符串值(确保在最后一个索引处输出为 0 终止字符串 \0)f.e.:
char ch = toupper((unsigned char) cipher[tempLocation]);
strncat(output, &ch, 1);
  • 更改方法的签名,例如:
// message: is a string (pointer to char[] which is a string)
// enrypted: copy created string (output) at end of the method to encrypted instead of return output
// int is the return value - 0 success, != 0 failure
int encryptKey(char *message, char *enrypted)
  • 将结果复制到给定的字符内存:

代替:

string secretMessage = encryptKey(message);

做:

char secretMessage[512] = { 0 };

// no & needed ... a array is a pointer
if (encryptKey(message, secretMessage) != 0)
{
  printf("\n Something failed");
}

在你的方法结束时:

strcpy(encrypted, output);

就像其他人评论的那样,做整件事反复试验会让你一事无成。

希望这些提示足以让您弄清楚其余部分。

【讨论】:

  • @chux - 恢复 Monica 谢谢,是的,空的 {} 只在 c++ 中工作
  • 注意:return output; 仍然是一个问题——返回局部变量的地址。
  • 告诉学生不要使用他们正在解决问题的课程所需的图书馆是一个糟糕的建议,无论您对图书馆的看法如何。你可以告诉他们图书馆只是早期课程的临时拐杖,以后应该放弃。
  • CS50课程揭示了字符串的本质at this point in lecture 4 of the course
  • 再次感谢所有提示(添加了 unsigned char 演员表)。
猜你喜欢
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 2019-03-15
  • 2020-08-15
  • 2019-06-09
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多