gpt4 book ai didi

C strcmp() 没有按预期返回 0

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:10 24 4
gpt4 key购买 nike

我已经尝试让 strcmp 在以下程序中返回 true 很多天了,我已经阅读了 strcmp 的手册页,读,写...我有其他人的帖子遇到了完全相同的问题。下面的源代码只是一个让我很沮丧的测试程序,有一些注释掉的行是我为使 strcmp 按预期工作所做的其他尝试。我已经使用“gdb -g”进行了编译,并且一次单步执行了一条指令。 printf 语句几乎说明了整个故事。我无法使 buf 或 bufptr 的值等于“t”。我简化了程序,让它一次一个地打印一个字符到屏幕上,无论读入什么文件,它们都按预期打印,但是,一旦我开始玩 strcmp,事情就会变得疯狂.我终其一生都无法找到一种方法来使 buf 中的值成为我期望的单个字符。当简化为 write(1,...) 调用时,它会将预期的单个字符写入标准输出,但将 strcmp 写入单个 't' 永远不会返回 0。!!!!!!先感谢您。我最初在那里没有 bufptr,正在对 buf 本身执行 strcmp,还尝试使用 bufptr[0] = buf[0],但仍然不一样。

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#define BUF_SIZE 1

void main(int argc, char *argv[])
{

char buf[BUF_SIZE];
int inputFd = open(argv[1], O_RDONLY);
char tee[] = "t";
int fff = 999;
char bufptr[BUF_SIZE];
// char *bufptr[BUF_SIZE];

while (read(inputFd, buf, BUF_SIZE) > 0) {
bufptr[0] = buf[0];
// bufptr = buf;
printf("********STRCMP RETURNED->%d\n", fff); // for debugging purposes
printf("--------tee is -> %s\n", tee); // for debugging purposes
printf("++++++++buf is -> %s\n", buf); // " " "
printf("@@@@@@@@bufptr is -> %s", bufptr); // " " "
write (1, buf, BUF_SIZE);


if ((fff = strcmp(tee, bufptr)) == 0)
printf("THIS CHARACTER IS A T");
}

close(inputFd);

}

最佳答案

str 系列函数需要字符串作为输入,这些字符串是存储以 null 结尾的字符序列的数组。但是,您没有在缓冲区中为空字符提供空间。要使缓冲区成为字符串,您需要为空字符添加空格并将值置零,以便它们以空字符结尾。

void main(int argc, char *argv[])
{
char buf[ BUF_SIZE + 1 ] = {0};
int inputFd = open(argv[1], O_RDONLY);
char tee[] = "t";

while (read(inputFd, buf, BUF_SIZE) > 0) {
if ( strcmp( tee, buf ) == 0 )
printf("THIS CHARACTER IS A T");
}

close(inputFd);
}

关于C strcmp() 没有按预期返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44400535/

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