gpt4 book ai didi

通过将数字替换为数字,将句子转换为数字。例如使用 strcmp 将 ABCD 转换为 2223

转载 作者:行者123 更新时间:2023-11-30 21:06:17 25 4
gpt4 key购买 nike

我正在尝试创建一个可以将字符替换为数字的应用程序。假设 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;
}

最佳答案

我修改了您的代码以使其正常工作,但未经过充分测试:

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

我希望这段代码能给你一些有用的东西

<小时/>
#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;
}

关于通过将数字替换为数字,将句子转换为数字。例如使用 strcmp 将 ABCD 转换为 2223,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com