Hi expert..Im newbie and i want to made a program to search a letter using a pointer..
Example there is a word WORLD
then the program will ask what letter u want to looking for..example its R and the program will said R is in index 3 and all R letter in the word is 1..CAN ANYBODY HELP ME
you have demonstrated some halved approach. If you used algorithm then it is more natural to use also standard functions sdt::begin and std::end. So either you should write function find yourself or you use all standard functions to make the approach more complete.:)
@Neo Takaredase
In fact you need two functions. One will search a given character in a character array and other will count how many times the character is present in the array.
I will show the first function
1 2 3 4 5 6 7
size_t find( constchar s[], char c )
{
constchar *p = s;
while ( *p && *p != c ) ++p;
return ( p - s );
}
In the main you will use the following test to determine whether the character is found.
1 2 3
size_t pos = find( word, 'R' );
if ( pos != std::strlen( word ) ) cout << "The letter " << 'R' << " is found at position " << pos << '\n';
#include <iostream>
#include <algorithm>
#include <conio.h>
usingnamespace std;
size_t find( constchar s[], char c )
{
constchar *p = s;
while ( *p && *p != c ) ++p;
return ( p - s );
}
size_t count( constchar s[], char c )
{
size_t n = 0;
for ( constchar *p = s; *p; ++p )
{
if ( *p == c ) ++n;
}
return ( n );
}
int main()
{ char word[100];
cout << "Enter a word : ";
cin>>word;
cout << "Enter a letter to search for : ";
char c;
cin >> c;
size_t pos = find ( word , c );
size_t count = count ( word ,c );
if ( pos != std::strlen( word ) ) cout << "The letter " << c << " is found at position " << pos << "The number of letter is" << count <<'\n';
getch();
}
You need no header <algorithm> because you do not use any function from it.
As for the program if you get a correct result then the program is correct. By the way the position of a letter starting from 0.
Also you have to check that the position is not equal to std::strlen( word ) that means (in case of the equality) that the character is not found. So to use function std::strlen you have to include header <cstring>