Hello, I am havig a problem counting certain characters ina string. What I want is to count the number of A's or a's in a string here's what I've done but it surely needs modifying
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
char a, A, c;
int total=0;
int i;
cout << "Please enter a phrase to count A's" << endl;
cin >> c;
while
{
total++;
}
cout << "The number of A's is: " << total << ".\n";
system ("pause");
return 0;
}
# include <iostream>
# include <cstdlib>// for system function
# include <cctype> // for tolower function
# include <cstdio> // for gets function
usingnamespace std;
int main ()
{
char phrase[100];/// Your phrase is more than one characters or word so it must be an array character
int total=0;
cout << "Please enter a phrase to count A's" << endl;
gets(phrase);// If you use the cin only the first is captured use gets function
// Your while miss the condition ,but I advise using the for statement
for(int i=0;i<phrase[i];i++)
{
if(tolower(phrase[i])=='a')
total++;
}
cout << "The number of A's is: " << total << ".\n";
system ("pause");
return 0;
}
I've tried giblits code and it doesn't work. Techno's work but my compiler can't read gets(phrase) so i changed it to gets_s. Anyway, I wanted to use for loop too but I'm restricted to only using while loop which kinda sucks.
use getline like I said... and you could of fixed my code easily I accidently mispelt input on line 6 so remove the t after in and I forgot to initialize count so put a blank line after line 8 and put int count = 0;
it will look like.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
int main()
{
std::string s_input("");
std::cout << "Please enter a string to find \'A\' in: " << std::endl;
std::getline( std::cin , s_input );
int count = 0;
for( constauto &it : s_input )
{
if( it == 'a' || it == 'A' ) ++count;
}
std::cout << "There are " << count << " \'A\'s in " << s_input << std::endl;
return( 0 );
}
I think @giblit 's code does not work for you ,because you dont have the latest version of the compiler you're using currently ,so that's why your compiler cannot recongnize the new for-rang loop,
for the gets function it should work perfectly fine ,if you're including the header <cstdio> which was I included abouve ,what is the compilator you're using right now