0

Hi all,
i'm writing this code that will prompt the user for a cstring of 25 chars...store it and prompt a char to find...then with a function search for that char from the cstring.

i got it working with a while loop, but only if i enter a char thats part of the cstring. if i enter a character that's not part of the cstring, that is invalid, i can't figure that out in the loop?

int find(char* p_cString, char valueToFind)
{
	cStringLength(p_cString);
	char* currentElementPtr = p_cString;
	currentElementPtr = strchr (p_cString, valueToFind);
	while (currentElementPtr != NULL)
	{
		cout << "\n\nSearch resulted in index of " << (currentElementPtr - p_cString) << ".\n";
		currentElementPtr = strchr (currentElementPtr + 1, valueToFind);
		cout << "(any number outside of 0 to " << cStringLength(p_cString);
		cout <<	" means that '" << valueToFind << "' does not exist in\n\"";
		cout << p_cString << "\")"".\n\n";
	}
	return 0;
}

any help would be greatly appreciated.
Thanks!

Edited by Nick Evan: Added code-tags

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by jonsca
0

Unless I misread what you need I think you are complicating things a bit more than needed. Try something like the following (I'll let you flesh it out):

for (int i = 0;p_cString[i] !='\0';i++)
	if(p_cString[i] == valueToFind)
	{

Since you know the length of your string you could use that as a limit on i also. This way you can display to the user the number of timse the character came up and its position each time.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.