gpt4 book ai didi

C 字符串比较

转载 作者:行者123 更新时间:2023-11-30 20:50:13 24 4
gpt4 key购买 nike

我一直在用 C++ 编码,而在 C 中完全是新的。为什么不起作用?我想通过输入 exit 来结束程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[4];

do{
printf( " -> " ) ;
scanf("%c", &command);
}while(&command != "exit");

return 0;
}

最佳答案

因为在 C 中你必须使用 strcmp 进行字符串比较。

在 C 语言中,字符串是一个以 '\0' 终止字节结尾的字符序列,其值为 0。

字符串“exit”在内存中看起来像这样:

+-----+-----+-----+-----+------+
| 'e' | 'x' | 'i' | 't' | '\0' |
+-----+-----+-----+-----+------+

where 'e' == 101, 'x' == 120, etc.

字符的值由ASCII Table的代码确定。 .

&command != "exit"

只是比较指针。

while(strcmp(command, "exit") != 0);

是正确的。当两个字符串相等时,strcmp 返回 0,即非零否则值(value)。参见

man strcmp

#include <string.h>

int strcmp(const char *s1, const char *s2);

DESCRIPTION

The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

但是您又犯了一个错误:

scanf("%c", &command);

此处您仅读取 1 个字符,此命令不是字符串。

scanf("%s", command);

这是正确的。

下一个错误是

char command[4];

它可以容纳最大长度为 3 个字符的字符串,因此 "exit" 不能适合缓冲区。

成功

char command[1024];

然后你可以存储一个带有 max 的字符串。长度为1023字节。

一般来说,想要保存长度为n的字符串,需要一个char数组至少 n+1 维。

关于C 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529148/

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