Count the frequency of a specific character in a text input - c++

int main()
{
char sentence;
int count;
cout << "Enter sentence: ";
cin >> sentence;
count = 0;
while ( sentence == 'b' || 'B' ) {
count++;
}
cout << "Number of b's: " << count * 1 << endl;
return 0;
}
The counting must also stop at all punctuation. I can't seem to get it to give me the correct count.

It's your while loop. The variable sentence is not changed inside the loop, so the loop may execute forever.
You may want to use std::string for a sentence and char for a character in the sentence.
Edit 1: Example
char letter;
cout << "Enter a sentence:\n";
while (cin >> letter)
{
// Check for sentence termination characters.
if ((letter == '\n') || (letter == '\r') || (letter == '.'))
{
break; // terminate the input loop.
}
// Put your letter processing code here.
} // End of while loop.

There are a couple suspicious points in your program:
char sentence;
cin >> sentence;
This looks like it would only be reading one character. You might want to getline() and save user input in a std::string
As for
while ( sentence == b || B ) {
This wouldn’t even compile since b and B are undefined. Maybe it should be
if ( cur_byte == ‘b' || cur_byte == ‘B’ )
count++
where cur_byte is some properly maintained iterator inside your string

#include <string>
Use string. string sentence; And create a for long as:
for(int i=0; i<sentence.length(); i++)
if(sentence[i] == b || B) count ++;
So simple ;) Good luck ;)
EDIT 1:
If you will only use while:
int count = sentence.length();
int count2 = 0;
while(count != 0)
{
if(sentence[count] == b||B) count2++
count--;
}
Good luck ;)

#include <iostream>
using namespace std;
int main()
{
char c;
int n = 0;
cout << "Enter sentence: ";
while (cin >> c && !ispunct(c)) if (tolower(c) == 'b') n++;
cout << "Number of b's: " << n << endl;
return 0;
}
Example:
Enter sentence: Two B or not two b, that is the question Bb.
Number of b's: 2

Related

alphabetic inputs run infinite loop

I wrote a function to squire number and try to cover all the input possibilities.
Overall it works fine with numeric input, but it starts a infinite loop of printing statements on screen when I enter alphabetical input.As all we know that inside computer single character like "A or a or b or B" so on is represented by integers and as i learned from my teacher that we can store single characters into a variable with integer data type. i am not talking about strings which means collection of characters . this program create problem with single character !
#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: \n";
cin >> num;
cout << "please enter the nmber you want to power the number with: \n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. \n" ;
option:
cout<< "\nPease type 'Y' to Enter the values again OR type 'c' to Exit ! \n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. \n";
}
}
return;
}
Better try to read the input in an std::string, then parse the string to check if you only have numeric characters and then use std::atoi to convert the string in integer. One last recomendation, avoid to use goto instructions, this practice make a code difficult to read.
#include <iostream>
#include <string>
#include <cstdlib>
bool OnlyNumeric(const std::string& numStr)
{
size_t len= numStr.length();
int i;
for (i=0;i<len && numStr[i] <='9' && numStr[i] >='0';i++) ;
return i == len;
}
int main()
{
std::string inputStr;
int num;
do{
std::cout << "Input number:\n";
std::cin >> inputStr;
}
while (!(OnlyNumeric(inputStr) && (num=std::atoi(inputStr.c_str())) ));
std::cout << "Your number is : " << num;
return 0;
}

input the letter f or any letter and cout an alphabet pattern like a abc abcd abcde abcdef but it only works if i press 0

So far nothing happens when you enter f it only works when 0 is entered but I want it so when you press f you get this a ab abc abcd abcde abcdef
#include <iostream>
using namespace std;
int main()
{
int f = 0;
int z;
cout << "";
while(cin >> f)
{
if(f == 0)
{
cout << "ABCDEF\nABCDE\nABCD\nABC\nAB\nA";
break;
}
}
}
The variable f is an int. When you press the key 'f', the cin istream tries to set the int to 'f', which isn't a number, so the conversion from a character to a number fails.
That failure sets the bad-bit in cin, which breaks out of the while loop.
Here's one way to make your program do what you want:
#include <iostream>
using namespace std;
int main()
{
char c = 0; // we want chars, not integers.
int z;
cout << "";
while (cin >> c)
{
if ('a' <= c && c <= 'z') // test for the range we want
{
// print all glyphs from a to 'c'
for (char i = 'a'; i <= c; ++i)
cout << i;
cout << '\n';
break;
}
}
}
Reading the input into a char is the easy bit: std::cin >> c for a char c will do it.
The fun bit is writing a portable way of printing the letters up to a certain character. Here's one way:
// Prints up to and including 'c'.
// Outputs the alphabet if 'c' is not a lower case letter.
void print(char c)
{
static const char s[] = "abcdefghijklmnopqrstuvwxyz";
for (std::size_t i = 0; s[i]; ++i){
std::cout << s[i];
if (s[i] == c){
std::cout << '\n';
return;
}
}
}
If you enter f you cause an error because it is expecting an integer. You can convert the a char to an integer. If you want to turn a result if you enter f you have to options:
1.
char input;
std:cin >> input;
if((int)input == 102){
.....
2.
char input;
std:cin >> input;
if(input == 'f'){
.....
EDIT:
If you want to print the Alphabet in descending order Michael Roy had a nice solutions but in accesnding order
if....
for(char i = input; i >= 'a'; --i)
cout << i - 32; //the 32 is for converting the lower case char into upper case
cout << '\n';
So in total it could look something like this:
char input;
std:cin >> input;
if('a' < input < 'z'){
for(char i = input; i >= 'a'; --i)
cout << i - 32;
cout << '\n';
}else{
cout << "Not a valid input";
}
System("Pause");//so the console doesn't close automatically

Can someone tell me why I am stuck in my validation loop after entering 'y' to continue?

Why am I getting stuck in my validation loop after hitting Y to continue? I have to use cin.get and can not use strings
This program collects input from a user and displays them by using a pointer with an array, I have to validate for negative numbers, letters and newline characters with the appropriate message
#include <iostream>
#include <iomanip>
using namespace std;
void validateUserInput(char *userInputCharArray, int &strLength);
int const ARRAY_SIZE = 100;
int main()
{
char *userInputCharArray = nullptr;
char yes = NULL;
int lengthOfInput;
//creating a dynamic array size 100
userInputCharArray = new char[ARRAY_SIZE];
//loop
do
{
int count = 0;
//user prompt and accept input
cout << "Please enter an integer >= 0 and press <ENTER>: " << endl;
cin.get(userInputCharArray, ARRAY_SIZE);
while(userInputCharArray[count] != ' ' && userInputCharArray[count] != '\0')
count++;
{
if(userInputCharArray[count] == ' ')
{
userInputCharArray[count] = '\0';
}
}
lengthOfInput = count;
validateUserInput(userInputCharArray, lengthOfInput);
cout << "Your number is: " << endl;
for(int i = 0; i < lengthOfInput; i++)
{
cout << userInputCharArray[i] - '0' << " ";
}
cout << endl;
cout << "Press y to continue or any other button to exit: " <<endl;
cin >> yes;
delete [] userInputCharArray;
userInputCharArray = nullptr;
userInputCharArray = new char[ARRAY_SIZE];
}while(yes == 'y' || yes == 'Y');
cout << "Thank you Good-Bye";
cout << endl;
delete [] userInputCharArray;
userInputCharArray = nullptr;
system("pause");
return 0;
}
Im getting stuck in my functions while loop
void validateUserInput(char *userInputCharArray, int &strLength)
{
int counter = 0;
while(*userInputCharArray < '0' || (*userInputCharArray >= 'A' && *userInputCharArray <= 'Z')
|| (*userInputCharArray >= 'a' && *userInputCharArray <= 'z')
|| *userInputCharArray == 0)
{
cout << "Please enter a positive integer and press <ENTER>: " <<endl;
cin.get(userInputCharArray, ARRAY_SIZE);
}
while(userInputCharArray[counter] != ' ' && userInputCharArray[counter] != '\0')
counter++;
if(userInputCharArray[counter] == ' ')
{
userInputCharArray[counter] = '\0';
}
strLength = counter;
}
According to the while loop you have here, you will keep on calling in.get so long as the first character that you read in is a digit or an alphabetic character. So, if you start your input with one of those characters, you will loop forever.
I'd suggest that you get input a line at a time and then parse what you get.
cin.get(*userInputCharArray);
Will extract one character only, therefore the terminator character '\0' will not be part of userInputCharArray.
Change it to read a line at a time and parse the input. If you're still having issues, you can flush your input buffer before each read like so:
cin.ignore(10, "\n");
cin.get(userInputCharArray, ARRAY_SIZE);

How to form a string out of multiple chars in a for loop

The first part of my code is used to receive a single string input from the user and replace certain characters in that word using string class member functions. This part was easy for me to figure out, but I can't seem to figure out how to form a new string out of these changed characters since I will need to use this string for further manipulation later on in my code.
This is problematic since the for loop outputs single char variables that can't be manipulated as a single string.
#include <iostream>
#include <string>
using namespace std;
int main(){
string word;
char letter;
int i;
cout << "Enter a word: ";
cin >> word;
cout << "\n";
for ( i = 0; i < word.size(); i++)
{
if ( word.at(i) == 'e')
{
word.at(i) = '3';
}
if ( word.at(i) == 'i' )
{
word.at(i) = '1';
}
if ( word.at(i) == 'x' )
{
word.at(i) = '*';
}
cout << word.at(i);
}
cout << "\n";
}
As my code currently stands, a user might, for example, input the string "cheese" and receive the output ch33s3. However this output is not a string; it is an assortment of chars without a space to separate them. I can't continue my code any further with my for loop output remaining as it currently is.
Edit: I realize now that I already have what I need, but confused myself into thinking the scope wouldn't apply outside my for loop. Thanks for the quick and easy answers.
You were pretty much done already:
#include <iostream>
#include <string>
using namespace std;
int main(){
string word;
char letter;
int i;
cout << "Enter a word: ";
cin >> word;
cout << "\n";
for ( i = 0; i < word.size(); i++)
{
if ( word.at(i) == 'e')
{
word.at(i) = '3';
}
if ( word.at(i) == 'i' )
{
word.at(i) = '1';
}
if ( word.at(i) == 'x' )
{
word.at(i) = '*';
}
}
cout << word << "\n";
}
As it turns out, your work is already done for you. Your variable "word" would hold the value "ch33s3" after the loop ends.
The variable word contains the altered string and can be manipulated as such. It appears that you already have what you need.
Also - you may already know this - but you don't need the "at" function to accomplish what you're doing here. You can index the string like an array. For example:
word[i] = 'e';
cout << word[i];
However this output is not a string
Did you mean to use std::ostringstream instead of std::cout to receive the results?
The word.at(i) = xxx; statements already manipulated the word string, and you have it.
Here's a sample to show how to get a std:string result, without manipulating word directly:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string word;
char letter;
int i;
std::cout << "Enter a word: ";
std::cin >> word;
std::ostringstream leetWord;
for ( i = 0; i < word.size(); i++) {
if ( word[i] == 'e') {
leetWord << '3';
}
else if ( word[i] == 'i' ) {
leetWord << '1';
}
else if ( word[i] == 'x' ) {
leetWord << '*';
}
else {
leetWord << word[i];
}
}
// Here you can refer to the ostringstream::str() function to
// get a string
std::string theWantedString = leetWord.str();
std::cout << word << " => " << theWantedString << std::endl;
}
See the working sample.

probably wrong if statement, not moving to next row after input

When I run my program, I have to type how many rows do I want in my output. I have a limit from 1 to 100 rows. Each row is a task with a name of the task followed by increasing number, example: Task1:, Task2, .... When I type something into input, it must convert input string /see the code below - except the code in main();/.
My problem is that when I type first input, it should go to next task/next row/ but it doesnt. I type for example 10 strings but they dont go each to next task but they stay in one task..hope you understand now.
#include<iostream>
#include<string>
#include <ctype.h>
using namespace std;
void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl;
}
int main(){
const int max = 100;
string input;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
while (cin >> input)
Convert (input);
while(input.size() > max)
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
while(input.size() > max)
cin >> input;
while (cin >> input)
Convert(input);
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
Your first if in Convert will always fail on a non-underscore and return. I don't think that's what's intended. Agree with other answer on the while cin loop. The next two whiles should be if's apparently. Step thru this code with a debugger and watch it line by line and see where it fails. You've got multiple issues here, and I'm not entirely sure what the intent is.
Edit - I didn't parse the extra parenthesis correctly. The first if in convert is actually okay.