gpt4 book ai didi

c - 我如何从读取中获取ascii字符?

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:54 25 4
gpt4 key购买 nike

在这个程序中,我需要将我读取的 ascii 字符的频率存储在一个数组中(以便打印最频繁的字符)。问题是我从 read 中得到的不是 ascii(很可能是某种地址)所以在 buf[] 数组中我越界了。谁能告诉我这方面的帮助?

    #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<strings.h>

#define MODEMDEVICE "/dev/ttyAMA0"

#define FALSE 0
#define TRUE 1

volatile int STOP=FALSE;

int main()
{
int fd,c, res=0,i;
struct termios oldtio,newtio;
int buf[128] ;

for (i=0;i<128;i++) buf[i]=0;

fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
if (fd <0) {perror(MODEMDEVICE); exit(-1); }

tcflush(fd, TCIFLUSH);
while (STOP==FALSE) { /* loop until we have a terminating condition */
int r=read(fd,&c,1);
write(1,&c,1);
if (c=='\n') {
for(i=0;i<128;i++)
if (res < buf[i] )
res = buf[i];
printf("first char %d \n", res);
}
else {
buf[c]++;

}
}
}

最佳答案

int c 创建一个大概 4 字节的变量。它没有被初始化,因此它可能包含任何垃圾。

然后是系统调用

read(fd,&c,1)

更改这些字节之一,可能是最高或最低,同时保持其他字节不变。现在你有 3 个字节的随机垃圾加上来自 fd 的一个字节的组合,放在 c 的某个地方。

然后您尝试从该组合中获得意义。

如果将 c 定义为 char,事情可能会更好:

char c;

关于c - 我如何从读取中获取ascii字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951734/

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