gpt4 book ai didi

c - 将消息翻译为 B1FF 语言时出现问题

转载 作者:行者123 更新时间:2023-11-30 16:15:25 24 4
gpt4 key购买 nike

I wrote a program that translates a sentence into B1FF language. When i enter a message and hit enter, it doesn't give any output, using a specific piece of code. I can make it work when i write the code in a specific way but i choose to write it in another way, which should be similar. Can you explain why it doesn't work?

This piece of code works for my program and i thought it was similar to the other code:

for(;(message[len] = getchar()) != '\n';) len++;

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define N 50

int main() {
char message[N];
int len=0;
printf("Enter message: ");
/*this is the part that is not working and i have no idea why. I
thought it's similar to the other code i provided*/
do {
message[len] = getchar();
len++;
} while (message[len] != '\n');

for(int i = 0; i < len; i++) {
switch(toupper(message[i])) {
case 'A': putchar('4'); break;
case 'B': putchar('8'); break;
case 'E': putchar('3'); break;
case 'I': putchar('1'); break;
case 'O': putchar('0'); break;
case 'S': putchar('5'); break;

default: putchar(toupper(message[i])); break;
}
}
printf("!!!!!!!!!!");
return 0;

}

最佳答案

关于示例代码的一些观察。这里

len++;
message[len] != '\n' /* at this stage message[len] contains Garbage not the valid char due to len++ */

lenmessage[len] != '\n' 语句之前递增,然后访问数组的 len+1 个字符导致未定义行为。为了避免这种情况,您可以检查如下

message[len-1] != '\n'

接下来,message 数组不是以 null 结尾的。从循环中出来后,以 '\0' 结束数组。例如

message[len] = '\0';

最好的方法是在声明自身的同时初始化 char 数组。例如

char message[50] = {}; /* zeroed the whole array */

关于c - 将消息翻译为 B1FF 语言时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57115990/

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