Hello. I'm writing code that will take a string as input, store it in an array, then analyze the array to see how many of the user input character there are in the string they put in. Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
#include <string>
using namespace std;
string phrase[256];
char x;
/**********************************************************************
* This function will ask for the character from the user.
***********************************************************************/
void getCharacter()
{
cout << "Enter a letter: ";
cin >> x;
}
/**********************************************************************
* This function asks for the text to be analyzed.
***********************************************************************/
void getString(string phrase[])
{
cout << "Enter text: ";
cin >> phrase[256];
}
/**********************************************************************
* This function analyzes the string to find how many of the character
* there are in it and displays that number.
***********************************************************************/
int findLetter(char x, string phrase[])
{
int counter = 0;
for (int i = 0; i < sizeof(phrase[256]) / 256; i++)
{
if (phrase[256].compare(phrase[i]) == 'x')
counter++;
}
cout << "Number of " << x << "'s: " << counter << endl;
return counter;
}
/**********************************************************************
* Main calls all the functions and displays how many of the character
* there are.
***********************************************************************/
int main()
{
getCharacter();
getString(phrase);
findLetter(x, phrase);
return 0;
}
|
I have quite a few problems, but here are my main ones:
The compiler won't let me leave the original call for a string array to have a blank size. Is there any reason for this? It says that unless I do that, it has a linker error.
The for loop in my findLetter function isn't even running. I don't know how it's printing the final part with the number of characters, but it's printing that and skipping the for loop.
Finally, I had to use the str.compare() in order to compare the character, but I know that's not the easiest way to do it, nor have we learned about that in the class I'm taking.
What am I missing? According to what they told me, I should be able to write my for loop like this:
1 2 3 4
|
for (int i = 0; phrase[i]; i++)
{
cout << phrase[i];
}
|
But when I write that out, the compiler freaks out. What's going on? I'm using Visual Studio 2015. Is there a problem with my compiler?
Thanks.