You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LZW编码实现问题:含空格字符串输入与压缩结果计数

LZW编码实现问题解决方案

问题1:带空格字符串读取异常及空输入错误

问题现象

  • 使用scanf("%s")读取输入字符串时,无法识别空格,遇到空格即停止读取;
  • 改用scanf("%[^\n]%*c", string)后,未输入任何字符直接回车,会输出Compressed Message is: <0>。

原因分析

  • scanf("%d", &choice)读取菜单选项后,输入缓冲区会残留换行符,后续的scanf("%[^\n]%*c")会直接读取到该换行符前的空内容,导致string为空;
  • Encoding函数中直接执行Prefix[0] = *string,当string为空时,*string是字符串结束符'\0',其ASCII码为0,因此输出<0>。

解决代码修改

  1. 修正字符串读取的scanf,添加前导空格跳过空白字符(包括残留的换行符):
// 原代码
scanf("%s",string);
// 修改为
scanf(" %[^\n]%*c", string);
  1. 在Encoding函数开头增加空输入判断,避免无效处理:
void Encoding (char string[SIZE], char comp[SIZE])
{
    // 新增空输入判断
    if (string[0] == '\0') {
        strcpy(comp, "");
        return;
    }
    
    char Prefix[SIZE]="";
    char Char[SIZE]=""; 
    // 剩余原有代码...
}

问题2:统计压缩结果中的编码数量

问题需求

对于格式如<23><65><765>的压缩结果,需要统计其中的编码个数(示例中返回3)。

实现思路

每个编码对应一个<符号,只需遍历压缩后的字符串,统计<的出现次数即可。

实现函数

新增统计函数:

int countEncodedCodes(char *comp) {
    int count = 0;
    while (*comp != '\0') {
        if (*comp == '<') {
            count++;
        }
        comp++;
    }
    return count;
}

使用示例

在需要统计的地方调用该函数,比如在main函数的case1中添加:

case 1:{
    printf("\nenter your string to encode:");
    scanf(" %[^\n]%*c", string);
    Encoding(string, comp);
    printf("Compressed Message is: %s\n", comp);
    if (strlen(comp) > 0) {
        printf("Encoded code count: %d\n", countEncodedCodes(comp));
    }
    break;
}

完整修改后关键代码片段

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#define SIZE 100

typedef struct ASCII {
    char str[SIZE];
    int code;
    struct ASCII* point;
} Dictionary;

Dictionary *head=NULL;

// 原addDiction、checkDiction、ReturnPrefix、freeDictionary函数保留不变

void Encoding (char string[SIZE], char comp[SIZE])
{
    if (string[0] == '\0') {
        strcpy(comp, "");
        return;
    }
    
    char Prefix[SIZE]="";
    char Char[SIZE]=""; 
    
    Prefix[0]=*string;
    int Codeword=256;
    int c=1;
    
    for(int i=1; string[i] != '\0'; i++)
    {
        Char[0]=string[i];
        
        if (checkDiction (head, Prefix, Char) != -1)
        {
            strcat(Prefix, Char);
        }
        else
        {
            if(Prefix[1]== '\0')
            {
                char t[10]=" "; 
                sprintf(t, "<%d>", Prefix[0]);
                strcat(comp, t);
            }
            else
            {
                int codew=ReturnPrefix(head, Prefix);
                char t[10]=" ";
                sprintf(t, "<%d>", codew);
                strcat(comp, t);
            }
            addDiction (&head, Prefix, Char, Codeword);
            Codeword++;
            strcpy(Prefix, Char);
        }
    }
    
    if(Prefix[1]== '\0')
    {
        char t[10]=" ";
        sprintf(t, "<%d>", Prefix[0]);
        strcat(comp, t);
    }
    else
    {
        int codew=ReturnPrefix(head, Prefix);
        char t[10]=" ";
        sprintf(t, "<%d>", codew);
        strcat(comp, t);
    }
}

// 原print、countAfter函数保留不变

int countEncodedCodes(char *comp) {
    int count = 0;
    while (*comp != '\0') {
        if (*comp == '<') {
            count++;
        }
        comp++;
    }
    return count;
}

int main()
{
    int choice;
    bool state= true; 
    char string [SIZE]="";
    
    printf("\n\n\n              Welcome!\n");
    
    while(state){
        printf("\n\n----------LZW encoding procesor--------\n");
        printf("\n\nTo encode your string enter:1\n");
        printf("To print Corresponding Table enter:2\n");
        printf("To find Threshold enter:3\n");
        printf("To delete string enter:4\n");
        printf("to exit enter:0\n");
        printf("NOTE: To encode a new string, previouse string should be deleted, Thank You!\n");
        printf("================================\n\n");

        printf("enter your choice:\t");
        scanf("%d",&choice);
        char comp[SIZE]="";
        
        switch(choice)
        {
            case 1:{
                printf("\nenter your string to encode:");
                scanf(" %[^\n]%*c", string);
                Encoding(string, comp);
                printf("Compressed Message is: %s\n", comp);
                if (strlen(comp) > 0) {
                    printf("Encoded code count: %d\n", countEncodedCodes(comp));
                }
                break;
            }
            
            // 原case2、case3、case4、case0、default分支保留不变
        }
    }
    free(head);
    return 0;
}

内容的提问来源于stack exchange,提问作者tierd programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:37:01