【问题标题】:Converting a sentence into number by replacing digits into numbers. for instance ABCD to 2223 using strcmp通过将数字替换为数字来将句子转换为数字。例如 ABCD 到 2223 使用 strcmp
【发布时间】:2018-04-09 03:00:27
【问题描述】:

我正在尝试创建一个可以将字符替换为数字的应用程序。假设 A = 2 和 F=3 如果我写 AFAF = 2323 应该是结果,请帮助。

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

int main(){

char *test;
char *result;
int i,e = 0;
int ch;

    while((ch = getchar()) != '\n'){
            if(e < 5){
                    *test++=ch;
                    e++;
            }
    }
    *test = '\0';

    for(i =0; i < 5; i++){
            if(strcmp(test++,"A") == 0 || strcmp(test++,"B")==0 || strcmp(test++,"C")==0){
                    result[i] = "2";
            }else if (strcmp(test++,"D") == 0 || strcmp(test++,"E")== 0 || strcmp(test++,"F")== 0){
                    result[i] = "3";
            }
    }
    for(i = 0; i<5;i++){
            printf("%s", result[i]);
    }
return 0;
}

【问题讨论】:

  • 为什么使用strcmp进行基于字符的比较?
  • 您应该只使用something == 'A' 来达到您的目的。在程序运行之前,您还需要修复其他几个错误。例如未初始化的指针、printf 中的错误格式说明符、赋值中的错误指针类型等。
  • 您没有为测试和结果变量分配内存(调用 malloc)并使用它们..

标签: c arrays string function strcmp


【解决方案1】:

我修改了你的代码让它工作,没有经过全面测试:

  1. 您缺少对输入的完整性检查
  2. 无需strcmp 进行基于字符的比较
  3. 您正在使用指向数组的指针 - 但您没有为它们分配内存,请参阅 malloc 文档和示例 - mu 代码使用静态分配,因此我避免使用它们
  4. test++ 将在评估时更改值,因此您的比较部分..这是错误的,它不起作用
  5. 如果您使用%s,则在打印字符串时无需循环 - 如果您想打印chars 并避免空终止,请使用%c 以空终止(\0)代替

我希望这段代码能给你一些帮助


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

int main(){

    char test[6]; //your test array is of fixed size + 1 for the '\0' char
    char result[6]; //if you use a pointer you must malloc the array - but in this case use static allocation it is easier
    int i,e = 0;
    int ch;

    while((ch = getchar()) != '\n'){
        if(e < 5){
            test[e]=ch; //no need for pointer here
            e++;
        }
    }
    test[e] = '\0'; //null terminator at the end of the string - not really needed at all

    printf("%s", test);
    for(i =0; i < 5; i++){
        if ( test[i] == 'A' || test[i] == 'B' ||test[i] == 'C' )
            result[i] = '2';
        else if ( test[i] == 'D' || test[i] == 'E' ||test[i] == 'F' )
            result[i] = '3';
    }
    result[5] = '\0'; //add the null terminator - only needed if you wish to print with %s

    /* you can just print the string no need for a loop here */
    printf("%s", result);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-10-12
    • 2018-01-02
    • 2015-06-01
    • 2014-04-03
    • 2022-11-14
    • 2014-05-20
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多