Reputation: 39
Im trying to make a program that loops through a string and count how many of each letter is used. Problem is that i cant get the array to save it properly. Any help is greatly appreciated.
int main()
{
string textRad = "";
int histogram[ANTAL_BOKSTAVER];
getline(cin, textRad);
berakna_histogram_abs(histogram, textRad);
cout << histogram[0] << endl;
cout << histogram[2];
return 0;
}
void berakna_histogram_abs(int histogram[], string textRad)
{
for(int i = 0; i < ANTAL_BOKSTAVER; i++)
{
histogram[i] = 0;
}
for(int i = 0; i < textRad.length(); i++)
{
for(int j = 0; j < ANTAL_BOKSTAVER; j++)
{
int antal = 0;
string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(char(toupper(textRad.at(i))) == alfabet.at(j))
{
antal++;
}
histogram[j] = antal;
}
}
}
Upvotes: 0
Views: 159
Reputation: 10936
Taking account of Javid's and Tjofras' answers here is a complete, simpler, and safer example:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
void berakna_histogram_abs(std::vector<int>& histogram, const std::string& textRad);
int main() {
const int ANTAL_BOKSTAVER = 26; //Assumed value.
std::string textRad;
std::vector<int> histogram(ANTAL_BOKSTAVER, 0);
std::getline(std::cin, textRad);
std::transform(textRad.begin(), textRad.end(), textRad.begin(), toupper);
berakna_histogram_abs(histogram, textRad);
std::cout << histogram[0] << std::endl;
std::cout << histogram[2];
return 0;
}
void berakna_histogram_abs(std::vector<int>& histogram, const std::string& textRad) {
static std::string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::size_t s = alfabet.length();
for(std::size_t i = 0; i < s; ++i) {
histogram[i] = std::count(test_string.begin(), test_string.end(), alfabet[i]);
}
}
Upvotes: 1
Reputation: 2096
The way you use the antal variable is wrong. you would never get more then 1 for each letter. Something like this should work better:
void berakna_histogram_abs(int histogram[], string textRad)
{
for(int i = 0; i < ANTAL_BOKSTAVER; i++)
{
histogram[i] = 0;
}
for(int i = 0; i < textRad.length(); i++)
{
for(int j = 0; j < ANTAL_BOKSTAVER; j++)
{
string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(char(toupper(textRad.at(i))) == alfabet.at(j))
{
histogram[j]++;
}
}
}
}
And i would also recommend using english for variables/method names.
Upvotes: 0
Reputation: 2935
Try this:
int main()
{
string textRad = "";
int histogram[ANTAL_BOKSTAVER];
getline(cin, textRad);
berakna_histogram_abs(histogram, textRad);
cout << histogram[0] << endl;
cout << histogram[2];
return 0;
}
void berakna_histogram_abs(int histogram[], string textRad) {
for(int i = 0; i < ANTAL_BOKSTAVER; i++)
histogram[i] = 0;
string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int i = 0; i < textRad.length(); i++) {
for(int j = 0; j < alfabet.length(); j++)
if(char(toupper(textRad.at(i))) == alfabet.at(j))
histogram[j]++;
}
}
Upvotes: 0