【发布时间】: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