Count number of occurrences in string c++? - c++

I'm used to java, and struggle with basic syntax of C++ despite knowing theory. I have a function that is trying to count the number of occurrences in a string, but the output is a tab bit weird.
Here is my code:
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
main
* Start
* prompt user to enter string
* call function
* stop
*
* count
* start
* loop chars
* count charts
* print result
* stop
*/
using namespace std;
void count(const char s[], int counts[]);
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
Here is the output:
Enter a string: Dylan
You entered Dylan
b: 1Times
c: 1Times
d: 2Times
f: 1Times
h: 1Times
i: 1229148993Times
j: 73Times
l: 2Times
n: 2Times
p: 1Times
r: 1Times
v: 1Times
Any help you can give me would be greatly appreciated. Even though this is simple stuff, I'm a java sucker. -_-

Your counts is uninitialized. You need to first set all of the elements to 0.

You need to zeros the counts vector.
Try
counts[26]={0};

I don't know about java, but you have to initialize your variables in C/C++. Here is your code working:
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
for(int i=0; i<26; i++)
counts[i]=0;
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}

Related

Print an string in an 2d array c++

I want to ask how can I print the word Chessmaster in 2d array randomly each letter of the word? I tried with srand but I don't how to combine it with characters. Can someone help me with is code. Also, can I create random letters in a 2d array without rand ?
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX = 11;
using namespace std;
void printwo()
{
char word[MAX] = {'c', 'h', 'e', 's', 's', 'm', 'a', 's', 't', 'e', 'r'};
int c, i, n, letters;
cout << "I will print this word " << word << " sepereate" << endl;
srand(time(NULL));
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[i] << "]"
<< "["
<< "]";
cout << endl;
}
}
}
int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;
if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
exit(0);
}
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <time.h>
const int MAX = 11;
using namespace std;
// Generate a random number between min and max (inclusive)
// Assumes std::srand() has already been called
// Assumes max - min <= RAND_MAX
int getRandomNumber(int min, int max)
{
static constexpr double fraction { 1.0 / (RAND_MAX + 1.0) }; // static used for efficiency, so we only calculate this value once
// evenly distribute the random number across our range
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}
void printwo()
{
char word[MAX+1] = {"chessmaster"}; //If you are using C-style strings then you should declare +1 space
//int c, i, n, letters; not needed
cout << "I will print this word " << word << " sepereate" << endl;
//srand only gives a seed to yout tand function, you need to call std::rand() to get a random integer
//use the function getRandomNumber above that is based on rand() and gives you the possibility to select range
srand(time(NULL));
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Print a random letter["
<< "][" << word[getRandomNumber(0,10)] << "]"
<< "["
<< "]";
cout << endl;
}
}
}
int main()
{
int c;
cout << "Hello user press _1_ to continue" << endl;
cin >> c;
if (c == 1)
{
printwo();
}
else
{
cout << "Bye";
//exit(0); exit here not needed
}
return 0;
}
I wrote some comments.. please read them and ask me if you don't get something. I would suggest reading about C-style strings and rand() here:
Rand() - https://www.learncpp.com/cpp-tutorial/59-random-number-generation/
C-style strings(basically arrays of char) - https://www.learncpp.com/cpp-tutorial/66-c-style-strings/

No output after using strcmp()

I'm trying to make a program that asks the user to input a string then checks to see how many vowels and consonants are in the string, using c strings. Right now I'm working on the function that counts the vowels. I finally got it to were I don't have any errors, but my program just hangs up after choosing to count the vowels. Here is my code.
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
class VowelsandConsonants {
public:
int findVowels(char *cString, const int STRINGLEN) {
const int SIZE = STRINGLEN;
int vowelCount = 0;
char *str = cString;
char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 0; i < SIZE; i++) {
str[i];
for (int j = 0; j < SIZE; i++) {
vowels[j];
if (strcmp(vowels, str)) {
vowelCount++;
}
}
}
return vowelCount;
}
};
int main()
{
char *myString = nullptr;
const int STRLEN = 20;
int selection;
myString = new char[STRLEN];
VowelsandConsonants v;
cout << "Enter a string 20 characters or less." << endl;
cin.getline(myString, STRLEN);
cout << "Select the number of what you want to do." << endl;
cout << "1.) Count the number of vowels." << endl;
cout << "2.) Count the number of consonants." << endl;
cout << "3.) Count both vowels and consonants." << endl;
cout << "4.) Enter another string." << endl;
cout << "5.) Exit program." << endl;
cin >> selection;
if (selection == 1) {
cout << v.findVowels(myString, STRLEN);
}
delete[] myString;
return 0;
}
Am I approaching this the right way?
I recommend using a C-Style string containing the vowels, then using strchr to search it:
const char vowels[] = "aeiou";
const size_t length = strlen(cString);
unsigned int vowel_count = 0;
for (unsigned int i = 0; i < length; ++i)
{
if (strchr(vowels, cString[i]) != NULL)
{
++vowel_count;
}
}
There are other methods, such as using an array to hold the counts (and using the letter as an index) or std::map.

C++ rand() not working with string array

I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}

Making a program that counts the amount of occurrences for each letter in the alphabet issues

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
string text;
int i;
char x;
int n = 0;
int main(int argc, const char * argv[])
{
cout << "Enter some text: " << endl;
getline(cin, text);
for (x = 'a'; x <= 'z'; x++)
{
for (i = 0; i<= text.length(); i++)
{
if (text[i] == x)
{
n++;
cout << x << ": " << n << endl;
}
}
}
}
So I want it to print out the occurrence for each letter that appears in the string but instead, I am getting this:
Input: hello
Output:
e: 1
h: 2
l: 3
l: 4
o: 5
I understand why it is counting up each time it finds a letter, but how do I get it to display the number of times each one of those letters actually come up. For example this is what I want it to say:
e: 1
h: 1
l: 2
o: 1
In the start of each loop(x) you should reset n to 0.
Also you should move the statment
cout << x << ": " << n << endl;
From the second loop the end of the first loop

Can someone please tell me why this code doesnt print anything?

I have to write a code that compares three text files and i cant for the life of me find out why this wont print anything:
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
using namespace std;
int main (int argc, char *argv[])
{
ifstream mousefile;
mousefile.open(argv[1]);
string mouse_dna;
getline(mousefile, mouse_dna);
ifstream humanfile;
humanfile.open(argv[2]);
string human_dna;
getline(humanfile, human_dna);
ifstream unknownfile;
unknownfile.open(argv[3]);
string unknown_dna;
getline(unknownfile, unknown_dna);
int len = mouse_dna.size();
int mouseDistance = 0, humanDistance = 0;
for(int i=0; i<len; i++)
if(mouse_dna[i] != unknown_dna[i])
mouseDistance++;
return mouseDistance;
for(int i=0; i<len; i++)
if(human_dna[i] != unknown_dna[i])
humanDistance++;
return humanDistance;
double similarity_scoreH = (len - humanDistance) / len;
double similarity_scoreM = (len - mouseDistance) / len;
cout << "MouseCompare = " << similarity_scoreM << endl;
cout << "HumanCompare = " << similarity_scoreH << endl;
if (similarity_scoreH == similarity_scoreM)
cout << "identity cannot be determined" << endl;
else if (similarity_scoreH > similarity_scoreM)
cout << "human" << endl;
else if (similarity_scoreM > similarity_scoreH)
cout << "mouse" << endl;
}
It compiles properly, and doesn't give any errors, but when i rut it as:
./DNA mouseDNA.txt humanDNA.txt unknownDNA.txt
it still does nothing.
I appreciate any help. Thanks!
It doesn't print anything because it's returning before the instructions to print (return mouseDistance; or return humanDistance;). Make your function more verbose by printing progress messsages before each return statement.
As already has pointed out, you return too early. I modify your code:
I put brackets around the if block and for block.
I have a return statement at the end.
This is a start. You may have to add more checking, for example, if the file is open correctly.
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
using namespace std;
int main (int argc, char *argv[])
{
ifstream mousefile;
mousefile.open(argv[1]);
string mouse_dna;
getline(mousefile, mouse_dna);
ifstream humanfile;
humanfile.open(argv[2]);
string human_dna;
getline(humanfile, human_dna);
ifstream unknownfile;
unknownfile.open(argv[3]);
string unknown_dna;
getline(unknownfile, unknown_dna);
int len = mouse_dna.size();
int mouseDistance = 0, humanDistance = 0;
for(int i=0; i<len; i++)
{
if(mouse_dna[i] != unknown_dna[i])
{
mouseDistance++;
}
}
for(int i=0; i<len; i++)
{
if(human_dna[i] != unknown_dna[i])
{
humanDistance++;
}
}
double similarity_scoreH = (len - humanDistance) / len;
double similarity_scoreM = (len - mouseDistance) / len;
cout << "MouseCompare = " << similarity_scoreM << endl;
cout << "HumanCompare = " << similarity_scoreH << endl;
if (similarity_scoreH == similarity_scoreM)
cout << "identity cannot be determined" << endl;
else if (similarity_scoreH > similarity_scoreM)
cout << "human" << endl;
else if (similarity_scoreM > similarity_scoreH)
cout << "mouse" << endl;
return 0;
}
You use arg[1], arg[2], and arg[3]. You may want arg[0], arg[1], and arg[2].