【问题标题】:Why I keep getting a random character at the end of my string in C?为什么我总是在 C 中的字符串末尾得到一个随机字符?
【发布时间】:2020-07-08 02:34:31
【问题描述】:

我正在尝试编写一个程序,该程序根据加密字母表对用户键入的任何内容进行加密。但是,当打印出结果时,我在结果字符串的末尾不断得到一个额外的随机字符。我试图用 '\0' 结束我的结果字符串,但它不起作用。请发送一些帮助!

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

int find_index(char a[], int num_elements, char value);

int main (void)
{
    string ori = "abcdefghijklmnopqrstuvwxyz"; // original alphabet
    string key = "ZYXWVUTSRQPONMLKJIHGFEDCBA"; // encryption alphabet
    
    string plain_text = get_string("plaintext: ");
    
    // count the number of characters in plain_text
    int count = 0;
    for (int i = 0; plain_text[i] != '\0'; i++)
    {
        count++;

    }
    
    char answer [count + 1];
    answer[count+1] = '\0';
    
    for (int i = 0; i < count ; i++)
    {
        // if the character is not in alphabet, just add it to answer
        if (isalpha(plain_text[i]) == false)
        {
            answer[i] = plain_text[i];
        }
        else
        {
            // take the original character in plain text
            char ori_char = plain_text[i];
            // find it index in the orginal alphabet
            int index_ori = find_index(ori, 26, tolower(ori_char));
            // find the corresponding character in encryption alphabet
            char res_char = key[index_ori];
            if islower(ori_char)
            {
                res_char = tolower(res_char);
            }
            else
            {
                res_char = toupper(res_char);
            }
            // update the char list
            answer[i] = res_char;
        }
    }
    printf ("ciphertext: %s\n", answer);
}

int find_index(string a, int num_elements, char value) // find index of a character in a string
{
    int x = -1;
    for  (int i=0; i < num_elements; i++)
    {
        if (a[i] == value)
        {
            x = i;
            return x;
        }
    }
    return(x);  /* if it was not found */
}

【问题讨论】:

  • 这是\0 而不是/0

标签: c string cs50 non-ascii-characters


【解决方案1】:

char answer [count + 1]; answer[count+1] = '\0'; 是 UB,因为它试图访问数组外部。

也许还有其他问题。

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 2020-12-22
    • 2023-03-17
    • 2013-01-15
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多