Outputting vowels and consonants from strings in c++ - c++

This is the question I have to answer:
Write a program that declares two strings: s1 and s2.
Initialize both of them using getline(cin, string) function.
a) Output the length of each string
b) Output the first appearance of a letter a in the first string
c) Output the first appearance of a letter b in the second string
d) Output the first word of each string
e) Output the last word of each string
f) Output first sentence reversed
g) Output second sentence with the words reversed ( the last word goes first, second last second, and so on)
h) Output the total number of vowels in the first sentence
i) Output the total number of consonants in the second sentence
This is what I have so far:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1,s2,s3;
int blank = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int s2temp = 0;
cout << "enter two sentences" <<endl;
getline (cin, s1);
getline (cin, s2);
s3=s2;
// a
cout << "the length of the first string is " << s1.length() << endl;
cout << "the length of the second string is " << s2.length() << endl;
// b
cout<<"the first appearance of the letter 'A' in the first string is ";
cout << s1.find("a");
cout <<endl;
// c
cout<<"the first appearance of the letter 'B' in the second string is ";
cout << s2.find("b");
cout <<endl;
// d
int s1_first = s1.find(" ");
int s2_first = s2.find(" ");
cout << "the first word in the first string is " << s1.substr(0,s1_first) <<endl;
cout << "the first word in the second string is " << s2.substr(0,s2_first) <<endl;
// e
cout << "the last word in the first string is " << s1.substr(s1.find_last_of(" "), s1.length()-1) <<endl;
cout << "the last word in the second string is " << s2.substr(s2.find_last_of(" "), s2.length()-1) <<endl;
// f
for(int i = s1.length()-1; i >= 0; i--)
cout <<s1.substr (i,1)<<endl;
// g
return 0;
}
I’ve tried a few different things for g, h, and i, but none have worked, so I thought I’d ask for help.

One method for counting vowels is to make a string containing vowels:
static const std::string vowels = "aeiouAEIOU";
Next, for each character in your string, search for it in the vowels string:
unsigned int vowel_count = 0;
const size_t length = text.length();
for (unsigned int i = 0; i < length; ++i)
{
const char c = text[i];
if (vowels.find(c) != std::string::npos)
{
++vowel_count;
}
}
This can be applied to consonants as well.
The code can be modified for those who are not allowed to use std::string.
Another method is to use std::map.

Related

checking for character pair in array

I have a character array that produces a random array of lowercase letters in the length that the user inputs. my problem is that after the array of random letters is produced the user inputs a pair of charaters(two letters) and my code should check if that pair is in the random array that was produced. it worked fine when it just checked for one letter but when i introduced the second one it does not work.I would appreciate any help.
#include <ctime>
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(NULL));
int i, num;
char letter1, letter2, ch, r;
const char chars[]="abcdefghijklmnopqrstuvwxyz";
std::cout << "How many letters do you want in your string? ";
std::cin >> num;
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
std::cout << "\nWhat letter pair would you like to find? ";
std::cin >> letter1 >> letter2;
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
}
First, you are not storing your randomly generated chars
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
This just writes a random char in ch and displays it on the console with each iteration. You don't store your data, ch just contains the last random char after your loop ends and everything else is lost.
The part where you want to search is double wrong.
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
This isn't inside a loop, i is simply always going to be num-1.
The array you are checking is chars which is your const array containing "abcdefghijklmnopqrstuvwxyz". This doesn't contain your randomly generated chars.

My c++ program doesn't complete and closes

This program counts the number of times a specific character appears in a string. The compiler shows me an incomplete output without displaying how many times the character shows in the input then closes abruptly
Enter a string (up to 50 characters): k;kl;kl;k;kljhh
Enter a character and I will tell you how many
times it appears in the string: k
k appears Press any key to continue...
I'm using VS community.
// This program demonstrates a function, countChars, that counts
// the number of times a specific character appears in a string.
#include <iostream>
using namespace std;
int countChars(char *, char); // Function prototype
int main()
{
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
char letter; // The character to count
// Get a string from the user.
cout << "Enter a string (up to 50 characters): ";
cin.getline(userString, SIZE);
// Get a character to count occurrences of within the string.
cout << "Enter a character and I will tell you how many\n";
cout << "times it appears in the string: ";
cin >> letter;
// Display the number of times the character appears.
cout << letter << " appears ";
cout << countChars(userString, letter) << " times.\n";
return 0;
}
//****************************************************************
// Definition of countChars. The parameter strPtr is a pointer *
// that points to a string. The parameter Ch is a character that *
// the function searches for in the string. The function returns *
// the number of times the character appears in the string. *
//****************************************************************
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
Unable to reproduce on Ubuntu. Perhaps a windows issue?
#include <iostream>
#include <iomanip>
class T590_t
{
std::stringstream ssin;
public:
T590_t() = default;
~T590_t() = default;
int exec(int , char** )
{
ssin << "k;kl;kl;k;kljhh\nk"; // for consistent behavior, use stringstream for input
// the letter ------------^
const int SIZE = 51; // Array size
char userString[SIZE]; // To hold a string
// Get a string from the user.
std::cout << "\n Enter a string (up to 50 characters): ";
(void)ssin.getline(userString, SIZE);
std::cout << "\n '" << userString << "'" << std::endl; // echo input
// Get a character to count occurrences of within the string.
std::cout << "\n Enter a character and I will tell you how many times it appears in the string: ";
char letter = '\0'; // The character to count, initialized
ssin >> letter;
std::cout << " '" << letter << "'" << std::endl; // echo input
// Display the number of times the character appears.
std::cout << "\n " << letter << " appears "
<< countChars(userString, letter) << " times.\n";
return 0;
}
private: // methods
int countChars(char *strPtr, char ch)
{
int times = 0; // Number of times ch appears in the string
// Step through the string counting occurrences of ch.
while (*strPtr != '\0')
{
if (*strPtr == ch) // If the current character equals ch...
times++; // ... increment the counter
strPtr++; // Go to the next char in the string.
}
return times;
}
}; // class T590_t
int main(int argc, char* argv[])
{
T590_t t590;
return t590.exec(argc, argv);
}
with output:
Enter a string (up to 50 characters):
'k;kl;kl;k;kljhh'
Enter a character and I will tell you how many times it appears in the string: 'k'
k appears 5 times.
You can pass an array of characters and its size instead:
int GetCharCount(char[], const int, const char);
int main(){
char text[] = "Hello there!";
cout << GetCharCount(text, strlen(text), 'e') << endl;
cout << endl << endl;
cin.get();
return 0;
}
int GetCharCount(char pTxt[], const int size, const char c){
int count = 0;
for(int i(0); i != size; i++)
if(c == pTxt[i])
count++;
return count;
}

Traversing an Inputted String and Returning a Specific Amount of Letters Within the String

I am working on a program that has the user input a letter then a string. Once the string is inputted the program should traverse the string and return the amount of the specific letter within the string. Here is the code I have so far:
#include <iostream>
using namespace std;
void countLetters(char letter[]);
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
char letter[256];
countLetters(letter);
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters(char Letter[])
{
char text[] = " ";
int count = 0;
cout << "Enter a letter: ";
cin >> letter;
cout << "Enter text: ";
cin >> text;
cin.getline(text, 256);
for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
{
if(text[i])
{
count++;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
}
/*
The output should be:
Enter a number: e
Enter a string: Hello, programming is fun
Number of 'e's: 1
*/
I have tried researching this and have found no help through this method of counting the amount of letters within the string the user inputs. Any help is appreciated, thank you.
Most issues have been pointed out in the comments. Here's a fixed version:
#include <iostream>
using namespace std;
void countLetters();
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
// You create an array in the function, don't need one here, too
// char letter[256];
countLetters();
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters()
{
// Your method creates an array of only 2 bytes
//char text[] = " ";
char text[256];
int count = 0;
// You forgot to declare letter
char letter;
cout << "Enter a letter: ";
cin >> letter;
// Reading the char leaves a new line. Consume. cin.ignore is another way
cin.getline(text, 256);
cout << "Enter text: ";
cin.getline(text, 256);
// Overly complicated
//for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
for (int i = 0; text[i]; i++)
{
// Compare to letter
if (text[i] == letter)
{
count++;
}
// This needs to be outside the loop
//cout << "Number of '" << letter << "'s: " << count << endl;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
In C++, it's almost always better to use std::string instead of raw char arrays, but I'll assume this is an assignment and arrays are required.

how to initialize the recursive function for length

int countChars(string str)
{
int count = 0;
if (str == "")
return count;
else
{
count++;// add a character to the count
return count + countChars(str.substr(1));// function calls itself
}
}
I need to take the above function and call in in the program below and I'm not sure how to initialize it properly. Below is what I tried and it doesn't work. I'm not allowed to use the .length() because otherwise the program would be done.
int main()
{
char find = '\0';
string str;
int count = 0;
int length = int(countChars);
//ask the user for a sentence
cout << "Enter a sentence " << endl;
getline(cin, str);
//ask the user which letter they want the count of
cout << "Which letter would you like to find the number of appearances: " << endl;
cin >> find;
for (int i = 0; i < length; i++)
{
if (str[i] == find)
{
count++;
}
}
cout << "the letter " << find << " appears " << length << " times " << endl;
//waits for user to exit
system("pause");
cin.get();
}
It seems the function should count the number of appearances of a letter in a string. If so then it is declared and defined incorrectly. It has to have at least two parameters an object of type std::string and an object of type char.
Here is shown how such a recursive function can look
#include <iostream>
#include <string>
size_t countChars( const std::string &s, char c )
{
return s.empty() ? 0 : ( s[0] == c ) + countChars( { s, 1 }, c );
}
int main()
{
std::cout << "Enter a sentence ";
std::string s;
std::getline( std::cin, s );
std::cout << "Which letter would you like to find the number of appearances: ";
char c = '\0';
std::cin >> c;
std::cout << "The letter " << c
<< " appears " << countChars( s, c )
<< " times " << std::endl;
return 0;
}
The program output might look like
Enter a sentence My name is Alycia
Which letter would you like to find the number of appearances: a
The letter a appears 2 times
If you mean a function that just calculates the length of a string then it can look like
size_t countChars( const std::string &s )
{
return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}
and shall be called after the statement
getline(cin, str);

Practice in dealing with character arrays that end in the null terminator

Write a program that ask user to enter any sentence, up to a maximum of 50 characters. The program will then tell how many words are in the sentence and how many characters are in the sentence. Do not count the null character. The program will then display the sentence backwards. Program must use one function that will determine how many words are in the sentence and pass this information back via a return value function.
Sample output follows:
Enter some sentence:
This is fun!
Your sentence has 3 words.
And your sentence has 12 characters.
Your sentence backwards is as follows:
!nuf si sihT
*****I have most of it done just need a little help with counting characters and making the function work*****
#include <iostream>
#include <string>
using namespace std;
int Words(char Line[]);
int main ()
{
string text;
cout << "Enter some Sentence: ";
getline(cin, text);
text = string(text.rbegin(), text.rend());
cout << "Your sentence backwards is as follows: " << text << endl;
return 0;
}
int Words (char Line []);
{
int CharCount = 0;
const int Size = 50;
char Sentence [Size];
int WordCount = 0;
cout << "Enter Some Sentence: ";
cin.getline(Sentence, 50);
for (int i =0; Sentence[i]!='\0'; i++)
{
if (Sentence[i] == ' ')
{
WordCount++;
}
}cout << "The number of words = " << WordCount+1 <<endl;
return 0;
}
You can use an istringstream constructed from the user input sentence coupled with the stream extraction operator to count the words.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int words(string sentence)
{
istringstream in{sentence};
string one;
int count = 0;
while(in >> one)
++count;
return count;
}
int main()
{
cout << words("just two") << '\n';
cout << words("A whole bunch of words!") << '\n';
cout << words("ONE!!!!") << '\n';
return 0;
}