Wrong looping/Reading C++ - c++

I am just learning C++. I wrote a program that shows the repeated letters in a string (I also have to count how many times it the letter gets repeated). The thing is when I run my code to get the repeated letters from the sentence. It runs okay for some but not some. For example: "hi there" runs good returning h and e, but something like "people are nice" returns peeeeee.The repeated letter should be shown only once. Point the problem out to me please. I assumed it had to do with the looping but can't figure it out exactly.
void repeatWord(string sentence)
{
for(int i=0; i<sentence.length(); i++)
for(int j=i+1; j<sentence.length(); j++)
if((!isspace(sentence[i]))&&(sentence[i] == sentence[j])){
cout<<sentence[i]<<endl;
}
return;
}

The problem is your inner loop. It displays the letter once every time it's encountered. Also, you do not break out of the loop after seeing a duplicate, so you get an exponential mess.
A better way is to just record how many times you've seen a letter. That requires just one loop and an array:
int count[256] = {0};
for( int i = 0; i < sentence.length(); i++ ) {
char c = sentence[i];
if( isalpha(c) && count[c]++ == 1 ) cout << c;
}
Instead of the array, you can use std::set. That would be more appropriate if you were handling Unicode. However, we're just dealing with a char here, which is 8 bits on almost every architecture you're likely to be practising on.
A little bonus of doing it this way is that you compute the letter frequencies. You can output these as follows:
for( int c = 0; c < 256; c++ ) {
if( count[c] ) cout << (char)c << " : " << count[c] << endl;
}
If you want to output case-insensitive counts, one way to do it is like this:
for( int c = 'a'; c <= 'z'; c++ ) {
int total = count[c] + count[toupper(c)];
if( total ) cout << (char)c << " : " << total << endl;
}

Getting rid of repeating letters is easy: just insert into a <set> or delete the letters after you see them. Inserting into a set is more efficient however:
set<char> letters;
for(int i=0; i<sentence.length(); i++)
for(int j=i+1; j<sentence.length(); j++)
if((!isspace(sentence[i]))&&(sentence[i] == sentence[j])){
letters.insert(sentence(i));
}
for(auto &i : letters)
cout << i << endl;

Related

How to count the number of times a letter shows up in a randomized string of alphabetical letters

I am trying to find the number of times each letter of the alphabet shows up in a randomized string that the user creates. I have all the code, minus the portion that would count each time a character is found. I have tried to use a couple of for...else loops to figure this out, but maybe I am just not learned to do it correctly, I keep either getting errors or a blank space under the rest of the output.
What I want is for the output to look like this:
A B C D E F G...
1 2 5 7 0 9 2...
Here is my code and my output so far:
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <map>
using namespace std;
int main() {
int i=0, n;
char alphabet[26];
char c;
char RandomStringArray [100];
srand(time(0));
cout <<"How many letters do you want in your random string (no less than 0, no more than 100): ";
cin >> n;
for (int i=0; i<=25; i++)
alphabet[i] = 'a' + i;
while(i<n) {
int temp = rand() % 26;
RandomStringArray[i] = alphabet[temp];
i++;
}
for(i=0; i<n; i++)
cout<<RandomStringArray[i];
cout<<"\n\n";
/*for(c = 'A'; c <= 'Z'; ++c)
cout<<" "<<c;
cout<<"\n";
*/
map<char,size_t> char_counts;
for (int i = 0; i < n; ++i) ++char_counts[RandomStringArray[i]];{
for (char ch :: alphabet) std::cout << ch << ' ';{
std::cout << '\n';
}
for (char ch :: alphabet) std::cout << char_counts[ch] <<'';{
std::cout << '\n';
}
}
}
std::unordered_map is good for this sort of thing. It's similar to the array approach of holding counts for each character but is more convenient to use, especially when the character ranges you're interested in are non-contiguous.
When you index a std::unordered_map the mapped value will be returned by reference, so you just increment it. If it doesn't exist it's created and default initialized (zero initialized for integer types).
So all you need to do is:
std::unordered_map<char, std::size_t> char_counts;
for (int i = 0; i < n; ++i) ++char_counts[RandomStringArray[i]];
After this, char_counts holds the total occurrence counts for all characters in the string. e.g. char_counts['a'] is the number of occurrences of 'a'.
Then to print them all out you could do:
for (char ch : alphabet) std::cout << ch << ' ';
std::cout << '\n';
for (char ch : alphabet) std::cout << char_counts[ch] << ' ';
std::cout << '\n';

How to count how many times a specific letter appears in a string? (C++)

I've been struggling with a homework assignment that counts the amount of instances a uppercase letters, lowercase letters, and numbers in a string. appears in a string.
I'm using a one-dimensional array with a constant size of 132 to store the entered string, and I need to use two functions. One needs to count the amount of letter occurrences in the string and the other function will execute the output something similar to above. I'm struggling most with the letter counting aspect of the program itself.
Currently, this is what my current homework resembles for the most part. It's a work in progress (of course) so errors in the code are very likely.
void LetterCount(char c_input[], int l_count)
{
// code to count letters
}
void CountOut(//not sure what should go here yet until counting gets figured out)
{
// code that handles output
}
int main()
{
const int SIZE = 132;
char CharInput[SIZE];
int LetterCount = 0;
cout << "Enter a string of up to 132 characters in size: ";
cin.getline(CharInput, SIZE);
cout << "You entered: " << CharInput << endl;
Count(CharInput);
CountOut(//not sure what goes here yet);
return 0;
}
The output would look something like:
a - 2
b - 1
c - 1
d - 0
e - 1
etc...
I've tried some experimentation with for loops to count the letters and have seen some examples of the function gcount(), but I haven't gotten anything to work. Does anyone have a suggestion as to how I would count the letters in an inputted string?
map is a very efficient data structure here
#include <iostream>
#include <map>
using namespace std;
int main(){
string str = "a boy caught 2 fireflies";
map<char, int> str_map;
for(auto x : str) ++str_map[x];
for(auto x : str_map) cout << x.first << ' ' << x.second << '\n';
}
What you want is to build a simple histogram, and it's pretty easy to do. Since what you're looking at is chars, and there can be 256 possible values of an 8-bit char (in practice your input string probably uses less, but we'll be conservative here because memory is cheap), you'll want to start with an array of 256 ints, all of them initialized to zero. Then iterate over the chars your string, and for each char in your string, use that char-value as an offset into the array(*), and simply increment that item in the array.
When you're done, all that remains is to iterate over the ints in the array and print out the ones that are non-zero, and you're done.
(*) you may want to cast the char to unsigned char before using it as an offset into the array, just to avoid any chance of it being interpreted as a negative array-index, which would result in undefined behavior (this is only an issue if your input string contains ASCII characters 128 and higher, so it may not matter in your case, but it's always good form to make code that does the right thing in all cases if you can)
As Jeremy frisner said you're building a histogram, but I disagree with the types used.
You'll want to declare your histogram like so:
size_t histogram[sizeof(char)*CHAR_BIT] = {0};
The size_t because you might overflow without it, and you need enough space if it's a nonstandard byte size.
As for printing it out. You should take a look at an ASCII table and examine which values you need to print out.
You could do it by comparing c-strings with other c-strings. But with chars and strings you can get errors like: "const *char cant be compared with strings". So you'll have to compare each c string(array) index with other c string indexes. In this program I use if statements to look for certain vowels. The way it works is that each "string alphabet_letter" is equal to it's respective lowercase and capital letters (for comparison). this is a very redundant way to do it and, if you want to count all total letters, perhaps you should try a different way, but this method doesn't use very complicated methods that require deeper understanding.
using namespace std;
int main(){
int vowel;
string A = "aA";
string E = "eE";
string I = "iI";
string O = "oO";
string U = "uU";
string str;
string str1;
bool userLength = true;
int restart = 0;
do{
cout << "Enter a string." <<endl;
getline(cin, str);
int VowelA = 0;
int VowelE = 0;
int VowelI = 0;
int VowelO = 0;
int VowelU = 0;
for(int x = 0; x < 100; x++){
if(restart == 1){
restart = 0;
x = 0;
}
if(A[0] == str[x]){
VowelA = VowelA + 1;
}
if(E[0] == str[x]){
VowelE = VowelE + 1;
}
if(I[0] == str[x]){
VowelI = VowelI + 1;
}
if(O[0] == str[x]){
VowelO = VowelO + 1;
}
if(U[0] == str[x]){
VowelU = VowelU + 1;
}
if(A[1] == str[x]){
VowelA = VowelA + 1;
}
if(E[1] == str[x]){
VowelE = VowelE + 1;
}
if(I[1] == str[x]){
VowelI = VowelI + 1;
}
if(O[1] == str[x]){
VowelO = VowelO + 1;
}
if(U[1] == str[x]){
VowelU = VowelU + 1;
}
int strL = str.length();
if(x == strL){
cout << "The original string is: " << str << endl;
cout << "Vowel A: "<< VowelA << endl;
cout << "Vowel E: "<< VowelE << endl;
cout << "Vowel I: "<< VowelI << endl;
cout << "Vowel O: "<< VowelO << endl;
cout << "Vowel U: "<< VowelU << endl;
cout << " " << endl;
}
}
char choice;
cout << "Again? " << endl;
cin >> choice;
if(choice == 'n' || choice == 'N'){userLength = false;}
if(choice == 'y' || choice =='Y')
{
restart = 1; userLength = true;
cin.clear();
cin.ignore();
}
//cout << "What string?";
//cin.get(str, sizeof(str),'\n');
}while(userLength == true);
}
/*
Sources:
printf help
http://www.cplusplus.com/reference/cstdio/printf/
This helped me with the idea of what's a vowel and whats not.
http://www.cplusplus.com/forum/general/71805/
understanding gets()
https://www.programiz.com/cpp-programming/library-function/cstdio/gets
Very important functional part of my program...Logic behind my if statements, fixed my issues with string comparison
What i needed to do was compare each part of one cstring with another c string
strstr compares two strings to see if they are alike to one another this source includes that idea-> https://www.youtube.com/watch?v=hGrKX0edRFg
so I got the idea: What is one c string was all e's, I could then compare each index for similarities with a c string whos definition was all e's.
At this point, why not just go back to standard comparison with strings? But you cant compare const chars to regular chars, so I needed to compare const chars to const chars
hence the idea sparked about the c strings that contained both e and E.
https://stackoverflow.com/questions/18794793/c-comparing-the-index-of-a-string-to-another-string
https://stackoverflow.com/questions/18794793/c-comparing-the-index-of-a-string-to-another-string
Fixed Error with using incremented numbers outside of involved forloop.
https://stackoverflow.com/questions/24117264/error-name-lookup-of-i-changed-for-iso-for-scoping-fpermissive
understanding the use of getline(cin, str_name)
https://stackoverflow.com/questions/5882872/reading-a-full-line-of-input
http://www.cplusplus.com/reference/istream/istream/getline/
http://www.cplusplus.com/forum/beginner/45169/
cin.clear - cin.ignore --fixing issue with cin buffer not accepting new input.
https://stackoverflow.com/questions/46204672/getlinecin-string-not-giving-expected-output
*/

Counting occurences of same array value in C++

I recently have been building a program where:
A user is asked to enter a number that will represent the size of a character array.
Then they are asked whether they will want the program to fill the values automatically, or they could press M so they could enter the values manually. They may only enter a-zA-Z values, or they will see an error.
At the end of the program, I am required to count every duplicate value and display it, for example:
An array of 5 characters consists of A;A;A;F;G;
The output should be something like:
A - 3
F - 1
G - 1
I could do this easily, however, the teacher said I may not use an additional array, but I could make a good use of a few more variables and I also can't use a switch element. I'm totally lost and I can't find a solution. I've added the code down below. I have done everything, but the counting part.
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
void main() {
int n, i = 0;
char masiva_izvele, array[100], masiva_burts;
cout << "Enter array size: ";
cin >> n;
clrscr();
cout << "You chose an array of size " << n << endl;
cout << "\nPress M to enter array values manually\nPress A so the program could do it for you.\n\n";
cout << "Your choice (M/A): ";
cin >> masiva_izvele;
if (masiva_izvele == 'M' || masiva_izvele == 'm') {
clrscr();
for (i = 0; i < n; i++) {
do {
cout << "Enter " << i + 1 << " array element: ";
flushall();
cin >> masiva_burts;
cout << endl << int(masiva_burts);
if (isalpha(masiva_burts)) {
clrscr();
array[i] = masiva_burts;
}
else {
clrscr();
cout << "Unacceptable value, please enter a value from the alphabet!\n\n";
}
}
while (!isalpha(masiva_burts));
}
}
else if (masiva_izvele == 'A' || masiva_izvele == 'a') {
clrscr();
for (i = 0; i < n; i++) {
array[i] = rand() % 25 + 65;
}
}
clrscr();
cout << "Masivs ir izveidots! \nArray size is " << n <<
"\nArray consists of following elements:\n\n";
for (i = 0; i < n; i++) {
cout << array[i] << "\t";
}
cout << "\n\nPress any key to view the amount of every element in array.";
//The whole thing I miss goes here, teacher said I would need two for loops but I can't seem to find the solution.
getch();
}
I would be very thankful for a solution so I could move on and forgive my C++ amateur-ness as I've picked this language up just a few days ago.
Thanks.
EDIT: Edited title to suit the actual problem, as suggested in comments.
One possible way is to sort the array, and then iterate over it counting the current letter. When the letter changes (for example from 'A' to 'F' as in your example) print the letter and the count. Reset the counter and continue counting the next character.
The main loop should run foreach character in your string.
The secondary loop should run each time the main "passes by" to check if the current letter is in array. If it's there, then ++.
Add the array char chars[52] and count chars in this array. Then print out chars corresponding to the array, which count is more than 1.
std::unordered_map<char, int> chars;
...
char c = ...;
if ('A' <= c && c <= 'Z')
++chars[c];
else if ('a' <= c && c <= 'z')
++chars[c];
else
// unexpected char
...
for (const auto p : chars)
std::cout << p.first << ": " << p.second << " ";
Assuming upper and lower case letters are considered to be equal (otherwise, you need an array twice the size as the one proposed:
std::array<unsigned int, 26> counts; //!!!
// get number of characters to read
for(unsigned int i = 0; i < charactersToRead; ++i)
{
char c; // get a random value or read from console
// range check, calculate value in range [0; 25] from letter...
// now the trick: just do not store the value in an array,
// evaluate it d i r e c t l y instead:
++counts[c];
}
// no a d d i t i o n a l array so far...
char c = 'a';
for(auto n : counts)
{
if(n > 0) // this can happen now...
{
// output c and n appropriately!
}
++c; // only works on character sets without gaps in between [a; z]!
// special handling required if upper and lower case not considered equal!
}
Side note: (see CiaPan's comment to the question): If only true duplicates to be counted, must be if(n > 1) within last loop!

Difficulty implementing limit to how many integers print on each line C++

I have seen this question around, but I am having difficulty implementing some of the solutions into my own code.
The program being worked on finds all the prime numbers in an array and times how long it takes to find all the prime numbers. One of the stipulations though is making the program print only 10 numbers per line. I have tried a couple different methods to get this to work, but none of them print how I need them to. Here is the current code:
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;
static const int N = 1000;
int main()
{
int i, a[N];
clock_t start = clock();
for (i = 2; i < N; i++) a[i] = i;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++) a[i*j] = 0;
start = clock() - start;
for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";
printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);
return 0;
}
I'm sure this is a simple mistake on my own part, or maybe I dont have the proper understanding on how this works. If anyone can shed some light on the subject it would be greatly appreciated, thank you.
Just create a new counter, to count the number of primes found.
int primes = 0;
for (i = 2; i < N; i++) {
if (a[i]) {
primes++;
cout << " " << i;
if ( primes % 10 == 0)
cout << "\n";
}
}
for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";
What this snippet does is not at all what you want it to do. If your whitespace is any indication, it looks like you expect this all to be nested in the same for loop. However, it's actually processed like this:
for (i = 2; i < N; i++) if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0) cout << "\n";
In other words, two completely separate statements. The first one goes through every element of a[i] and outputs them with a space. When that loop is done to completion, the second statement then checks a condition and adds a newline (that check is also broken, but I'll get into that later).
In order to break after every tenth element, the newline check needs to be processed for each element, or at least each element printed, rather than at the end.
So as written, what you seem to expect would actually be something like:
for (i = 2; i < N; i++) {
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";
}
The braces { } are important here, since they ensure that all the enclosed statements are part of the for loop and processed for each iteration, not just the single statement immediately following it.
Which brings up the second issue: That newline check does not do what you think it does. From your explanation, what you want is for the check to trigger on every tenth value printed, and add a newline. However, if ((i = 1) % 10 == 0)…doesn't do that. At all.
Rather than triggering on every tenth value, all if ((i = 1) % 10 == 0 does is set i to 1 (which will really break your for loop) and then never trigger since i = 1 will always return 1 anyway. It's just a convoluted way to do exactly what you don't want.
As Amadeus mentions, one easy way to implement this is just to use a counter that increments every time you print a value, and test against that instead:
for (i = 2; i < N; i++) {
if (a[i]) {
cout << " " << i;
primes++;
if (primes % 10 == 0)
cout << "\n";
}
}
Again, note the braces enclosing the three statements for the if (a[i]) clause. This ensures the increment and newline check only happen every time a value is actually printed, rather than for every iteration of the for loop.

C++:array functions

How can I write a program that reads in, a collection of characters from the key board and outputs them to the console. Data is input at random, but output selectively. Only unique characters are displayed at the console. Therefore, every character should be displayed once, no matter how many times it appears in the array.
For example, if an array
Char letterArray[ ] = {B,C,C,X,Y,U,U,U};
The output should be:
B,C,X,Y,U
This is what I have done so far...
char myArray [500];
int count = 0;
int entered = 0;
char num;
while (entered < 8)
{
cout << "\nEnter a Character:";
cin >> num;
bool duplicate = false;
entered++;
for (int i = 0; i < 8; i++)
{
if (myArray[i] == num)
duplicate=true;
}
if (!duplicate)
{
myArray[count] = num;
count++;
} // end if
else
cout << num << " character has already been entered\n\n";
// prints the list of values
cout<<"The final Array Contains:\n";
for (int i = 0; i < count; i++)
{
cout << myArray[i] << " ";
}
}
I believe you could make use of std::set<>.
"Sets are a kind of associative container that stores unique elements <...> elements in a set are always sorted from lower to higher following a specific strict weak ordering criterion set"
Looking through your code...
char myArray [500];
Why 500? You never use more than 8.
char num;
Confusing naming. Most programmers would expect a variable named num to be a numeric type (e.g. int or float).
while (entered < 8)
Consider replacing 8 with a constant (e.g. const int kMaxEntered = 8;).
cin >> num;
cin might be line-buffered; i.e. it does nothing until a whole line is entered.
for (int i = 0; i < 8; i++)
{
if (myArray[i] == num)
duplicate=true;
}
You're accessing uninitialized elements of myArray. Hint: your loop size should not be 8.
Consider using continue; if you find a duplicate.
if (!duplicate)
{
myArray[count] = num;
count++;
} // end if
else
cout << num << " character has already been entered\n\n";
Your // end if comment is incorrect. The if isn't ended until the else is done.
You may want to add braces around the else clause, or remove the braces from the if clause by combining its two lines into the one-line myArray[count++] = num;.
// prints the list of values
cout<<"The final Array Contains:\n";
for (int i = 0; i < count; i++)
{
cout << myArray[i] << " ";
}
You're printing the list every time you get a single input?
Don't use \n in text to cout unless you specifically want to micromanage buffering. Instead, use endl. Also, always put spaces around binary operators like << and don't randomly capitalize words:
cout << "The final array contains:" << endl;
for (int i = 0; i < count; i++)
cout << myArray[i] << " ";
cout << endl;
It would be much more efficient to create an array of size 128 (assuming you are dealing with ASCII) that is initialized with false. Every time you get a character, check its ASCII value and if the array is true on that value you don't print it. After that, update the value of the array on the character value to true. Something like:
bool *seenArray = new bool[128]();
void onkey(char input) {
if(((int)input) < 0) return;
if (!seenArray[(int)input]) {
myArray[count] = input;
count++;
seenArray[(int)input] = true;
}
}