gpt4 book ai didi

c++ - 使用指针作为参数在数组中查找 char 的索引

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

我有一个包含代码的主要功能:

int main()
{
const int SIZE = 80;
char ca[SIZE];
char * pc = ca;
int fPrints = 0;
int bPrints = 0;
int lengthChecks = 0;

ReadString(pc, SIZE);
char test = 'X';
int index = 0;
index = FindIndexOfCharacter(pc, test);
std::cout << test << " index " << index << std::endl;
test = 's';
index = 0;
index = FindIndexOfCharacter(pc, test);
std::cout << test << " index " << index << std::endl;

std::cout << "Press ENTER";
std::cin.get();
return 0;
}

读取输入的函数

void ReadString(char * c, int maxLength)
{
std::cout << "Enter a string less than " << maxLength << " characters." << std::endl;

std::cin.getline(c, maxLength);
}

这个函数应该通过使用指向数组的指针和一个测试值来返回数组中字符的索引并返回它

int FindIndexOfCharacter(char * c, char testVal) 
{
for (int i = 0; i < strlen(c); i++)
{
if (c[i] == testVal) {
return (int)i;
}
else
{
return -1;
}
}

}

两次搜索我得到的都是-1,我不确定我做错了什么。非常感谢任何帮助!

最佳答案

您在 FindIndexOfCharacter() 中返回得太早了!如果您遇到的第一个字符与 testVal 不匹配,FindIndexOfCharacter() 将提前返回。

尝试在 for 循环之后移动 return -1;;这样,只有在检查完 c 中的每个字符后,您才会返回 -1:

int FindIndexOfCharacter(char * c, char testVal) 
{
for (int i = 0; i < strlen(c); i++)
{
if (c[i] == testVal) {
return (int)i;
}
}

return -1;
}

关于c++ - 使用指针作为参数在数组中查找 char 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46964093/

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