How can I count alphabet characters efficiently? - c++

I initialized an array of characters, to put all uppercase and lowercase alphabets.
#include <iostream>
using namespace std;
int main () {
char c;
int cnt = 0;
cout << "Enter 0 to view the results " << endl;
char arr[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
while (1) {
for (int i = 0; i < 100000000; i++)
{
cin >> c;
if (c == arr[i]){
cnt++;
}
else if (c == '0'){
break;
}
else{
cout << "Please enter only characters!" << endl;
}
}
if (c == '0')
break;
}
cout << cnt << endl;
return 0;
}
I know that this code is inefficient.
How to write this code without break;?
If there's a better way to do that without using array, please mention it.

OP's question is very unclear but what I have understood from the comments is OP trying to find a simpler/similar way of counting someone's input for lowercase/upperCase alphabets and keep doing so until the user enters in a 0, I looked online and i found a better way and did some adjustments, it is pretty straight forward, here it is below.
#include <algorithm>
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
int main()
{
string s = "TEST";
while(s != "0"){
cout << " Enter text: ";
getline(cin, s);
size_t count_alpha = count_if(s.begin(), s.end(),
[](unsigned char ch) { return isalpha(ch); });
cout << "Alphabets: " << ( count_alpha)<<endl ;
}
}

Related

Check if string contain only letters

I have a trouble with a search through a string, if I enter a word with only letters, it's work as needs, I though, the code works, but when I add a number in work, the code work also, the question that, is possible to accept only if my var contains only letters, and if it will find a number or symbol, to go at begining of code?
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
label:
string var1 = "";
cout << "Enter a word: ";
cin >> var1;
for (int i = 0; i < var1.size (); i++)
{
int uppercaseCHar = toupper (var1[i]);
if (uppercaseCHar < 'A' || uppercaseCHar > 'Z')
{
goto endloop;
cout << endl;
} else
goto label;
cout << endl;
}
endloop:
cout << "Yout word contains only letters";
}
Output:
Enter a word: work
Enter a word: wro1
Enter a word: 123
Yout word contains only letters
Here is a solution that uses std::all_of:
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
int main()
{
bool isAllLetters = false;
do
{
std::string var1;
std::cout << "Enter a word: ";
std::cin >> var1;
// check if all characters are letters
isAllLetters = std::all_of(var1.begin(), var1.end(), [](char ch)
{ return std::isalpha(static_cast<unsigned char>(ch));});
if ( isAllLetters )
std::cout << "Your word contains only letters\n";
else
std::cout << "Your word contains stuff other than letters\n"
} while ( !isAllLetters );
}
Simple and efficient (C++17):
#include <algorithm>
#include <cctype>
#include <string_view>
bool all_of_alpha(std::string_view s)
{
return std::all_of(s.begin(), s.end(), [](unsigned char c) { return std::isalpha(c); });
}
Avoid using goto as it will complicate debugging code in larger program , here's another way :
int main()
{
while (true) {
bool flag = false; // to check for numeric entry
string var1; // not req to initialize
cout << "Enter a word (press exit to end): ";
cin >> var1;
for (int i = 0; i < var1.size(); i++)
{
int uppercaseCHar = toupper(var1[i]);
if (!std::isalpha(uppercaseCHar))
{
flag = true;
break;
}
}
if (var1.compare("exit") == 0) break;
if (flag) {
cout << "Your word contains number";
cout << endl;
}
else
{
cout << "Your word contains only alphabets";
cout << endl;
}
}
}
You can also use regular expressions which will simplify the code further.
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main () {
regex reg_obj("^[A-Z]+$");
string var;
start_label:
cout << "Enter a word: ";
getline(cin, var);
if(regex_match(var, reg_obj))
goto endlabel;
else goto start_label;
endlabel:
cout << "your word contains only letters\n";
return 0;
};
Allow me to offer a more modern idiomatic version and assuming you only care about detecting alphabetic characters in the ASCII character set.
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string a = "abcdefgh";
std::string b = "abcd3fgh";
std::string c = "abcdefg0";
auto is_alpha = [](unsigned char c){ return std::isalpha(c); };
bool aContainsAlphas = std::all_of(a.begin(), a.end(), is_alpha);
bool bContainsAlphas = std::all_of(b.begin(), b.end(), is_alpha);
bool cContainsAlphas = std::all_of(c.begin(), c.end(), is_alpha);
std::cout << std::boolalpha;
std::cout << "A: " << aContainsAlphas << '\n'; // true
std::cout << "B: " << bContainsAlphas << '\n'; // false
std::cout << "C: " << cContainsAlphas << '\n'; // false
}
This defines a lambda which is passed as an argument to std::all_of, which uses it to test each character:
auto is_alpha = [](unsigned char c){ return std::isalpha(c); };
This invokes is_alpha on each element between a.begin() and a.end(). If the end is reached without any mismatch for is_alpha, then true is returned.
bool aContainsAlphas = std::all_of(a.begin(), a.end(), is_alpha) != a.end();

Capitalize a letter regardless of spacing

Hi guys I have a question on this code I'm practicing cstrings with. I made a program that capitalizes the first letter of a sentence inputted by the user. I assumed that the user would put a space after placing a period so if the user typed in "im from. seattle" the output would be "Im from. Seattle". But if the user didn't put a space after the period it would be the second letter that would be capitalized and not the first like this "Im from.sEattle" . How do I get it to capitalize the first letter only regardless of spacing?
#include <iostream>
#include <cctype> //strlen, touper
#include <cstring>
using namespace std;
void funct(){
int length = 50;
char input[length];
cout << "Sentence Capitalization Machine Mk.1.\n";
cout << "Type a sentence for me to capitalize." << endl;
cin.getline(input, length);
cout << endl;
input[0] = toupper(input[0]);
int i=0;
while (i < strlen(input)){
i++;
if (input[i] == '.'){
input[ i + 2 ] = toupper(input[ i + 2 ]);
}
};
cout << input << endl;
}
int main(){
funct();
return 0;
}
Try This
#include <iostream>
#include <cctype> //strlen, touper
#include <cstring>
using namespace std;
void funct(){
int length = 50;
char input[length];
cout << "Sentence Capitalization Machine Mk.1.\n";
cout << "Type a sentence for me to capitalize." << endl;
cin.getline(input, length);
cout << endl;
input[0] = toupper(input[0]);
int i=0;
while (i++ < strlen(input)){
if (input[i] == '.' && input[i+1] == ' ' && i+2<strlen(input)){
input[ i + 2 ] = toupper(input[ i + 2 ]);
}else if(input[i] == '.' && i+1<strlen(input)){
input[ i + 1 ] = toupper(input[ i + 1 ]);
}
};
cout << input << endl;
}
int main(){
funct();
return 0;
}

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

How to loop through a string using find() C++

The loop in the program seems to execute at least once, even if there are no occurences of the substring. Why is this?
#include <iostream>
#include <string>
using namespace std;
int countSubstrings(const string& original_string, const string& substr) {
int number_of_ocurrences = 0;
int i = 0;
for (i = original_string.find(original_string, 0); i != string::npos;
i = original_string.find(substr, i)) {
number_of_ocurrences++;
i++;
}
return number_of_ocurrences;
}
int main() {
string input;
while (1) {
cout << "Enter a a line of text: ";
getline(cin, input, '\n');
cout << '\n';
cout << "Number of ocurrences of the word needle: ";
cout << countSubstrings(input, "needle") << '\n';
}
}
Initially when you set i in your for loop you have
original_string.find(original_string, 0)
So you are searching the string for itself which it will find. I believe you meant to have
original_string.find(substr, 0)

char uninitialized, isnumber method unidentified,

I'm having errors in my code below,
This is my code:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''";
char ch;
int i = 0;
while (Isnumber(ch)){ //here is the error
do{
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (ch>0 || ch < 9);
}
getchar();
}
two errors,
it says that identifier is unknown,
and
it says variable char is uninitialazed local variable,
change this while (Isnumber(ch)){ into do-while loop.
do{
.....
}while (Isnumber(ch))
The error is because ch is declared and it is used before initialized.
Also include #include <stdio.h>; for getchar();
Better do it in one loop:
do {
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (Isnumber(ch)); // should probably be isdigit(ch)
And before asking similar questions read this first (or buy a book).
Well I solved it using cin functions as below,
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
//char ch;
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
getchar();
}
I removed one while loop.
and used cin.fail and cin.good to avoid using IsNumber. And it worked.