gpt4 book ai didi

c - 使用字符作为哨兵但收到指针错误

转载 作者:行者123 更新时间:2023-11-30 15:20:23 31 4
gpt4 key购买 nike

我正在尝试编写一个循环来计算字符,直到收到某个哨兵值。哨兵值应该是 #,但我也尝试过 0 和 Z 并得到了相同的响应。

编译时,我收到第 16 行(调用哨兵的行)的“警告:指针和整数之间的比较”。

如果我没有定义哨兵,而是依赖于 while 语句中的逻辑运算符,那么我不会收到错误,但会出现无限循环。

谢谢!

#include <stdio.h>
int main()
{

#define SENTINEL '#'
char ch;
int chcount;

printf("Enter your text, terminate with a #:");
scanf("%s", &ch);
chcount = 0;

while (ch != SENTINEL)
{
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount +1;
printf("You have entered %d characters", chcount);
}
}
return(0)
}

最佳答案

使用 %s 格式说明符,scanf 需要 char 缓冲区的地址,您键入的字符串将复制到该地址。

并且您给出了单个字符的地址&ch,这显然不足以包含输入中的“单词”及其终止空字符。

此外,您的循环不会读取用户的输入。因此无限循环。

关于c - 使用字符作为哨兵但收到指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035254/

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