My c++ program doesn't complete and closes - c++

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;
}

Related

Outputting vowels and consonants from strings in 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.

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.

string and char variable was not declared in this scope C++

I want to create a program which is able to count the characters in a word.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
do
{
string inputWord = "";
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
do
{
char searchCh = '0';
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
}while(searchCh.size()<1 && searchCH.size()>1);
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
char ch = word.at(i);
// if the character matches the character we're looking for
if(searcCh==ch)
// increment counter
{
counter++; // counter = counter + 1
}
}
// output the number of times character appears
cout << "the word " << word << " contain character " << searchCh << "is" << counter;
return 0;
}
and I always get the error: inputWord was not declared.
What is the cause this error?
You should read about scopes. Variables in c++ have visibility and lifetime in scope, in which the were declared. For instance, inputWord is visible and exists only in the first do-while loop. Move its declaration above loop. Your code has many such errors. Moreover, I do not see, where is counter declared and it should be properly initialized.
You have mixed up a lot of variable names and used variables outside their scope.
Here is a working version of your code with a few debugs:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
string inputWord = "";
char searchCh = '0';
char ch;
int counter=0;
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
ch = inputWord[i];
// if the character matches the character we're looking for
if(searchCh==ch)
// increment counter
counter++; // counter = counter + 1
}
// output the number of times character appears
cout << "the word " << inputWord << " contain character " << searchCh << " is " << counter;
return 0;
}
You declared the inputWord as string, please check your compiler works for that or not because some compilers do not take the specifier "string". Also searchCh, counter and word is also missing from your program. First of all declare these variables properly.
you should define the "inputWord" before start the while loop , like this :
string inputWord = "";
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
because "inputWord" is inside the loop ,

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);

Char arrays and word counting

I have spent the last two hours trying different methods to prevent the APPCRASH error I keep getting when I run this program, but I am having NO luck whatsoever. Basically, all this is is a simple word counting program for an assignment. It works fine up until it is to display the word count that the program found when it ran. At this point, it just freezes for a second or two, then pops up with an APPCRASH error, and closes. I don't know WHY this is happening, anyone care to let me know where I am going wrong?
int main()
{
//word counting programs
char *userInput = new char;
input(userInput);
displayResults(wordCount(userInput), userInput);
return 0;
}
/***************************************
Definition of function - input *
prompts the user to input a sentence *
and stores the sentence into a char *
array. *
Parameter: char [] *
****************************************/
void input(char userInput[])
{
cout << "Enter a sentence (no more than 100 characters) and I will count the words:" << endl;
cin.getline(userInput, 101);
}
/***************************************
Definition of function - wordCount *
Accepts the input char array and counts*
the words in the sentence. Returns an *
int value with the word count. *
Parameter: char [] *
Returns: an int with the word count *
****************************************/
int wordCount(char* userInput)
{
int count = 0;
int words = 1;
if(userInput[0] == '\0')
{
words = 0;
}
else if(userInput[0] == ' ' || userInput[0] == '\t')
{
cout << "Error: can not use a whitespace as the first character!" << endl;
words = -1;
}
else
{
while(userInput[count] != '\0')
{
if(userInput[count] == ' ')
{
words++;
}
count++;
}
}
return words;
}
/***************************************
Definition of function - displayResults*
Displays the word count for the user *
entered input. *
****************************************/
void displayResults(int wordCountResult, char userInput[])
{
if(wordCountResult == -1)
cout << "Error reading input!" << endl;
else if(wordCountResult == 0)
cout << "Nothing was entered." << endl;
else
{
cout << "You entered: " << userInput << endl;
cout << "That contains " << wordCountResult << " word(s)!" << endl;
}
}
You're allocating 1 byte and expect to fit 100 bytes there:
char *userInput = new char;
You should write instead:
char *userInput = new char[101];
Better yet, avoid using raw pointers, C-strings and new. Use std::string in C++.
You allocated only one character instead of an array
char *userInput = new char;
try to change the line above at least to
char *userInput = new char[101];
The statement char *userInput = new char just creates a pointer to a char, not a string.
You have to use a character array here, if you don't prefer std::string.
change char *userInput = new char to char userInput[101].
Also, you have to declare your functions before main(), so that they can be called from main().
using namespace std;
void input(char userInput[]);
int wordCount(char* userInput);
void displayResults(int wordCountResult, char userInput[]);
int main()
{
//word counting programs
char *userInput = new char;
input(userInput);
displayResults(wordCount(userInput), userInput);
return 0;
}
/***************************************
Definition of function - input *
prompts the user to input a sentence *
and stores the sentence into a char *
array. *
Parameter: char [] *
****************************************/
void input(char userInput[])
{
cout << "Enter a sentence (no more than 100 characters) and I will count the words:" << endl;
cin.getline(userInput, 101);
}
/***************************************
Definition of function - wordCount *
Accepts the input char array and counts*
the words in the sentence. Returns an *
int value with the word count. *
Parameter: char [] *
Returns: an int with the word count *
****************************************/
int wordCount(char* userInput)
{
int count = 0;
int words = 1;
if(userInput[0] == '\0')
{
words = 0;
}
else if(userInput[0] == ' ' || userInput[0] == '\t')
{
cout << "Error: can not use a whitespace as the first character!" << endl;
words = -1;
}
else
{
while(userInput[count] != '\0')
{
if(userInput[count] == ' ')
{
words++;
}
count++;
}
}
return words;
}
/***************************************
Definition of function - displayResults*
Displays the word count for the user *
entered input. *
****************************************/
void displayResults(int wordCountResult, char userInput[])
{
if(wordCountResult == -1)
cout << "Error reading input!" << endl;
else if(wordCountResult == 0)
cout << "Nothing was entered." << endl;
else
{
cout << "You entered: " << userInput << endl;
cout << "That contains " << wordCountResult << " word(s)!" << endl;
}
}