gpt4 book ai didi

c - DEVC++ 中的错误(比较字符串和字符)

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

我正在尝试编写一个程序来计算字符串中出现的字母数量。我只想计算给定字符串上的字母 A 和 B。

char string[10];
int countA, countB;
gets(string);

for(int i = 0; i <strlen(string); i++){
if(string[i] == 'A')
countA++;
else if(string[i] == 'B')
countB++;
}

printf("%d %d", countA, countB);
return 0;

例如我的输入是:ABABA输出应该是 3 2 但是它为 countB 打印了不同的答案。我正在使用devc++。这是一个错误吗?

最佳答案

获得不同结果的原因:

早些时候,当您没有初始化变量 countAcountB 时,它们包含不确定的值。在代码中使用它们会引入未定义的行为。

两点:

  • 将变量初始化为零。 countAcountB

  • 并且不要使用 gets 而使用 fgets

<小时/>

我给你举个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(){
char string[10];
unsigned int countA=0, countB=0;
if( fgets(string,10,stdin) == NULL){
fprintf(stderr, "%s\n", "Error in string input");
exit(1);
}
size_t len = strlen(string);
if( len > 0 )
string[len-1]='\0';
for(size_t i = 0; i <strlen(string); i++){
if(string[i] == 'A'){
countA++;
}
else if(string[i] == 'B'){
countB++;
}

}

printf("%u %u", countA, countB);
return EXIT_SUCCESS;
}
<小时/>

注意:

  1. 还会询问您是否是全局变量。如果是这样,那么您可能不必担心初始化。它们将用 0 初始化。

  2. gets() 继续读取字符,直到遇到 \nEOF。并且在执行此操作时,缓冲区大小不受任何限制,从而存在缓冲区溢出的可能性。

关于c - DEVC++ 中的错误(比较字符串和字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47286964/

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