I have a main function which has the code:
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;
}
A function which reads the input
void ReadString(char * c, int maxLength)
{
std::cout << "Enter a string less than " << maxLength << " characters." << std::endl;
std::cin.getline(c, maxLength);
}
This function is supposed to return the index of a character in the array by using the pointer to the array and a test value and return it
int FindIndexOfCharacter(char * c, char testVal)
{
for (int i = 0; i < strlen(c); i++)
{
if (c[i] == testVal) {
return (int)i;
}
else
{
return -1;
}
}
}
All I get is -1 for both searches, I am not sure what I am doing wrong. Would appreciate any help!
intto anint? And you should probably not leave open the possibility that the compiler callsstrlen()on every iteration of the loop. More to the point, you should not useintfor sizes; that's whystd::size_texists (not that it matters until you start having strings > 2.1billionish characters long, but still...)lengthin the function which equals strlen() and then using it in the loop?for (std::size_t i = 0, len = strlen(c); i < len; ++i). Of course, first#include <cstddef>to get the declaration ofstd::size_t.