Hi guys,
This is a problem that I'm unsure how to solve.
Essentially, the task is to have the user enter in a sentence that ends with a period and then count how many times each letter is repeated up to that period. The program then outputs each letter in the sentence along with the amount of times it is repeated in decreasing order.
For example, if the user enters: "hello ." the output should be something similar to this:
l: 2
h: 1
e: 1
o: 1
-----------------------------------------------------------------------------
This is my plan so far:
1. Get input from user.
2. Get rid of any unnecessary spaces in input.
3. Store each letter into a vector v and keep storing letters up to the period.
4. Make two parallel vectors: one for letters and one for storing how many times
a particular letter is repeated.
5. Search vector v for repeats. If letter repeats, store it into vector "letters".
6. At the same time, keep track of how many times each letter is repeated and add '1' to my counting vector, which is parallel to my letters vector.
7. Sort the vector that does the counting from highest to lowest and sort the "letters" vector according to the same positions of the counting vector.
8. Output both vectors.
--------------------------------------------------------------------------
Does this seem like the way I should go about it? Or is there some way that is more easier/efficient? Sorry if this is long. Keep in mind that I have only been programming for 2 months so I do not have a vast of knowledge yet.
If you have any tips, let me know. Thank you. Here is my code up to now...
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 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <vector>
using namespace std;
string getInput(); //string input by user
void loadVector(vector<char>& v,string input);
int main()
{
vector<char> v;
string input = getInput();
loadVector(v, input);
vector<char> letters;
vector<int> count;
for (int i = 0; i < v.size(); i++)
{
cout << v[i];
}
return 0;
}
string getInput()
{
int period = 0;
string input;
do
{
cout << "Enter a sentence; Enter a period to end sentence: ";
getline(cin, input);
for (int i = 0; i < input.size(); i++)
{
if (input[i] == '.')
period += 1;
}
} while (input.size() == 0 || period == 0);
return input;
}
void loadVector(vector<char> &v, string input)
{
// loads vector, takes out spaces
// stops loading vector when input[i] == '.'
int i = 0;
do
{
if (input[i] != ' ')
v.push_back(input[i]);
i++;
} while (input[i] != '.');
}
|