My functions displays garbage, and some other times it displays clean result - c++

I have to count the number of upper case and lower case letters in a given line. For this assignment, I have to use arrays of characters terminated by \0, which is what I do. I use ascii code to identify lower case or upper case letters. However, the output is sometimes clean, sometimes not clean. Any help will be appreciated. Here is my code in Dev-C++. Thanks
#include <iostream>
#include<conio.h>
#include<cstring>
using namespace std;
int getline();
int isupper(char line[]);
int islower(char line[]);
int main()
{
int Month, last_digit; //initialize variables and char array
char temp[255];
getline();
getch();
return 0;
}
int getline()
{
char line[255];
cout << "Enter a sentence: ";
cin.getline (line, 255);
isupper(line);
islower(line);
getch();
return 0;
}
int isupper(char line[])
{
int y, i=0, k=0; int count_uppercase=0; char Uppercase_array[80];
cout<<endl<<"from isupper function"<<endl;
do
{
y=line[i++]; // Convert to int
if(y>64 && y<91) //if it is a Uppercase letter...
{
Uppercase_array[k]=line[i-1];
k++;
count_uppercase++; //increment the counter...
}
}
while(y);
cout<<"Uppercase letter = " <<Uppercase_array;
cout<<" number of uppercase = "<<count_uppercase<<endl;
cout<<"----------"<<endl;
return 0;
}
int islower(char line[])
{
int z, i=0, count_lowercase=0;
cout<<"from lowercase function"<<endl;
do
{
z=line[i++]; // Convert to int
if(z>96 && z<123) //if it is a Lowercase letter...
count_lowercase++; ////increment the counter...
}
while(z);
cout<<"number of lowercase = "<<count_lowercase<<endl;
getch();
return 0;
}
*******example1 of output*****
Enter a sentence: Good morning Dad, how ARE u?
from isupper function
Uppercase found in that line = GDARE√" number of uppercase = 5
----------
from lowercase function
number of lowercase = 16
************example2 of output*********
Enter a sentence: Good morning Dad how are u?
from isupper function
Uppercase letter = GD number of uppercase = 2
----------
from lowercase function
number of lowercase = 19

Look closely at this line:
cout<<"Uppercase letter = " <<Uppercase_array;
How does it know how many characters to output? You really should use std::string or std::vector<char>.
If you want the simplest fix, do this before you print: Uppercase_array[k]=0;. C-style strings have their ends marked with a terminating nul (zero byte) which tells functions that handle them how big they are.

If the "garbage" you are referring to is the √" in GDARE√", then the answer is to add the null-terminator \0 to the last char of Uppercase_array. That is, after the do/while loop, add Uppercase_array[k] = '\0'.

Related

I'm trying to change every letter in a given string with the letter following it in the alphabet using custom input

#include<iostream>
#include<string>
using namespace std;
string pass(string a){
int i=0;
string c[100];
char d;
while(a[i]!='\0'){
d = a[i];
if(d>='a'&& d<='z'){
d++;
c[i]=d;
}
else if(d>='A' && d<='Z'){
d++;
c[i]=d;
}
else{
c[i]=d;
}
i++;
}
for(int k=0; k<i; k++){
cout<<c[k];
}
}
int main(){
string x;
getline(cin,x);
pass(x);
return 0;
}
This is my solution.
I was looking for this kind of problem for a while but all I got was for pre-defined inputs. So, I passed a string from the main function.
I used a while loop to store every letter with the following letter (EX "a -> b") in another array "c". I then print the copied array using a loop.
Can we make it shorter?
You don't need to create a separate array called c. You can create an output string and iterate through it and increment the characters as shown below:
int main()
{
std::string input;
std::getline(std::cin, input);
std::string output(input);
for(char &c: output)
{
++c;
}
std::cout<<"input was: "<<input<<std::endl;
std::cout<<"changed string is: "<<output<<std::endl;
}
This is probably a better (and shorter) implementation for your code:
#include<iostream>
#include<string>
char NextAlpha(char character)
{
if (character == 'Z') return 'A';
else if (character == 'z') return 'a';
return character + 1; // Can be replaced by 'char((int)character + 1);'
}
int main() {
std::string input;
getline(std::cin, input);
for (int i = 0; i < input.size(); i++)
{
input[i] = NextAlpha(input[i]);
}
std::cout << input;
return 0;
}
The NextAlpha function returns the next alphabet by adding 1 to the character, but a more understandable version of it will be firstly converting the given character into an int as such:
(int)character
..which basically means getting the ascii value of that character. Now we add 1 to the int:
(int)character + 1
..and then convert it back to char
char((int)character + 1)
..but here I've not used this way because ++character looks a lot more cleaner.
The exceptions are defined before the return statement.
In the main function, we have a loop that iterates through all of the characters in the given string, and for each character, it does the following:
// Set the character at index 'i' of string 'input' to the next character in the alphabet.
input[i] = NextAlpha(input[i]);
Also, consider not using the following in your code:
using namespace std;
..as it's considered as bad practice.
First, you have an error in your code: your pass function is declared as returning a string but it doesn't return anything. Actually, you don't need to return anything – just pass the string by reference and make any required changes to its content "in place".
Second, you should be aware that the C++ Standard does not require that the Latin letters (lower- and upper-case) be represented by contiguous, sequential values (though in the ASCII system, used in most implementations today, they are).1
Third, you don't need so many loops, and you don't need to repeat the c[i]=d; statement in the if, else if and else blocks.
I'm not sure what you want to do with the 'z' and 'Z' characters but, in the code below, I'm assuming these should "wrap around", to 'a' and 'A', respectively.
So, here's a way to do what you want more concisely, and which doesn't depend on the implementation's specific representation values for Latin letters:
#include<iostream>
#include<string>
void pass(std::string& a) // Pass by reference (using "&") - changes will be kept.
{
const std::string Lowers{ "abcdefghijklmnopqrstuvwxyz" };
const std::string Uppers{ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };
size_t p;
for (auto& c : a) { // Note the "&" again: changes to c will be reflected in the corresponding "a" element
if ((p = Lowers.find(c)) != std::string::npos) {
c = Lowers[++p % 26]; // 'z' wraps round to 'a'
}
if ((p = Uppers.find(c)) != std::string::npos) {
c = Lowers[++p % 26]; // 'Z' wraps round to 'A'
}
}
}
int main()
{
std::string x;
std::getline(std::cin, x);
pass(x);
std::cout << x << std::endl;
return 0;
}
I have moved the output of the transformed string to the main function (and simplified it somewhat); generally, a function should do only the task it is set – which, in this case is to make the transformation. The subsequent display of the transformed string should be left to the calling module.
1 The EBCDIC system, for example, doesn't have the Latin letters in a contiguous sequence. You could use the std::islower(), std::isupper() and/or std::isalpha() functions to check for letters, but you would still need some sort of "data table" to determine what the 'next' character should be, unless you assume an ASCII or compatible encoding system.

How to get an easier way of generating the alphabet in C++?

i am trying to make a project,to experiment and learn C++, i didnt finish making it,but what it does is you type in a 3 or 4 (the variable noc) word and the program runs through all the possible (noc) letter words or nonsense, until it finds yours,so there are 2 factors: the length of the word or nonsense and what characters it can type,in my case i just want the alphabet
so here is my code:
#include <iostream>
#include <unistd.h>
using namespace std;
const int noc = 3;
int main() {
string used[noc];
string inp;
cin >> inp;
char albet[] = {'a','b','c'};
cout << "Starting..." << endl;
usleep(1);
string aiput = "";
while(aiput != inp){
for(int i = 0; i <= noc; i++){
aiput = aiput +
}
}
return 0;
}
currently i need the alphabet in the array called 'albet' (i come up with short words for what they mean its easy to forget tho)
so please can you get me a way to generate the alphabet in C++ quickly instead of having to type all of them one by one
When you need a character array you do not have to use individual character literals one by one, as in
char albet[] = {'a','b','c','d','e','f',... uff this is tedious ...};
You can use a string literal instead:
const std::string albet{"abcdefghijklmnopqrstuvwxyz"};
Took me ~10 seconds to type and compared to other answers, this does not rely on ASCII encoding (which is not guaranteed).
You could use std::iota, which is a great algorithm for this use case:
char albet[26] {};
std::iota(std::begin(albet), std::end(albet), 'a');
Here's a demo.
Note that this is not guaranteed to work in c++, unless you have ASCII encoding, but if you can rely on that you'll be fine.
Because all characters can be represented in ASCII codes ('a' starts at 97, all ASCII codes are int), you can simply make a loop to do that. For example:
char albet[26];
for (int ch = 'a'; ch <= 'z'; ch++) {
//do ch-'a' because we start at index 0
albet[ch-'a'] = ch;
}
and you are done!
Each letter has an ASCII representation. More about that here.
They are processed as numbers, being cast, and transformed into characters. For example, the letter a would be represented by the number 97 in decimal.
int aInAscii = 97;
printf("%c", (char)aInAscii);
The upper code would print, as you expect, the letter a. Why? Because we have just converted the number 97 to it's ASCII corresponding character.
So, in this way, we could generate the alphabet, using only numbers. A short example would be here (I preferred casting it before so that the starting and ending points are more clear.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<char> alphabet;
int aLetterCode = (int)'a'; // ASCII code for letter a (97)
int zLetterCode = (int)'z'; // ASCII code for letter z (122)
for (int charAsciiCode = aLetterCode; charAsciiCode <= zLetterCode; charAsciiCode++) {
alphabet.push_back((char)charAsciiCode);
}
for (char c : alphabet) {
cout << c << " ";
}
return 0;
}
You just can also make a function that returns a char, without generating an array, like this:
char get_alphabet_letter(unsigned int index, bool is_upper = false)
{
char letter = 97 + index;
if(is_upper) return letter - 32;
return letter;
}
from the given below code, you can generate uppercase alphabets of English. Uppercase alphabhets starts in ASCII from A = 65 to Z = 90. And, then, typecast the
integral value of uppercase alphabets into character using char().
#include <iostream>
using namespace std;
int main () {
char a[26];
for (int i=65 ; i<91 ; i++) {
int a[65-i] = char(i);
cout<<a<<endl;
return 0;
}

how to detect palindrome word using strcmp

Hye, I would really appreciate if anyone could answer this. The question is:
Write a program which will read a string of maximum 100 characters and rewrite its characters in reverse order. For example, the word GOOD should be written as DOOG and madam as madam. Check for palindrome words.
(A palindrome is a word whose meaning may be interpreted the same way in either forward or reverse direction)
Sample output:
Input your word: good
Reversed: doog
It is not a palindrome word
Input your word: madam
Reversed: madam`
It is a palindrome word
here is my source code :
> #include <stdio.h>
#include <string.h>
#define SIZE 100
int main()
{
char word[SIZE];
int length,x,result;
printf ("Input your word : ");
gets(word);
printf ("Reversed: ");
puts (strrev(word)) ;
length = strlen (word);
for (x=0; x<length; x++)
{
result= strcmp (strrev(word),word));
if (result==0)
printf("It's a palindrome word!");
else
printf ("It's not a palindrome word!");
}
return 0;
}
However, my source code stated above only managed to reverse the word but not be able to detect the correct palindrome word. Thank you in advance!
You don't need to generate the reverse word, just compare the characters :
bool isPalindrom(char word[], int sizeOfWord){
int j=sizeOfWord-1;
for (int i=0 ; i<sizeOfWord ; i++){
if(word[i] != word[j]){
return false;
}
j--;
}
return true;
}
int main()
{
char word[] = {'m', 'a', 'd', 'a', 'm'};
int sizeOfWord = sizeof(word)/sizeof(word[0]);
printf("%d", isPalindrom(word, sizeOfWord));
}
I have fixed some errors and worked ,I deleted for loop and fixed strcmp function

How to check using isdigit() if there more than one character

So, I'm still new on coding, and my friend is kindly taught me a lot and I want to be learn it quick, then he gave me this exercise to study in my home
He gave me this question about booking table number, so I tried to make it..
But I'm having trouble with this part checking the table number if it is a digit or not... I was searching on google on how, but they only give example on how to do it with single character.. So, I made an account then ask here xD
btw, the table max number is 25.
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<ctype.h>
bool checkDigit(char tablenum){
char digit[3];
int n;
int value = tablenum;
if(tablenum>0 && tablenum<10)
n=1;
if(tablenum>9 && tablenum < 26)
n=2;
for(int i=0;i<n;i++){
digit[i] = value%10;
value /= 10;
}
if(n==1){
printf("digit 0 = %d\nisdigit = %d\n",tablenum,isdigit(tablenum)); //just checking the isdigit value
if(isdigit(digit[0])!=0){
puts("It's digit");
return true;
}
else{
puts("It's not digit");
return false;
}
}
if(n==2){
printf("digit 0 = %d isdigit 0 = %d \ndigit 1 = %d isdigit 1 = %d\n",digit[0],isdigit(digit[0]),digit[1],isdigit(digit[1])); //checking the values too
if(isdigit(digit[0]) != 0 && isdigit(digit[1]) != 0){
puts("It's digits!");
return true;
}
else{
puts("It's not digits!");
return false;
}
}
else{
printf("It's not digit!")
return false;
}
}
int main(){
int num;
bool itsdigit;
do{
scanf("%d",&num);fflush(stdin);
itsdigit = checkDigit(num);
} while(itsdigit != 1 );
getchar();
return 0;
}
Input = "25" "1" "0" "test"
Output = "It's a digit" "It's a digit" "It's not a digit" "
Since the table is only 1 to 25
When I input "1" on it shows the right digit, but when it when in to isdigit() I keep getting 0.
I wonder what when wrong with this, and please give explanation.
And thanks before!
You have multiple problems.
Lets start by taking a closer look at these two lines:
checkDigit(num);
itsdigit = checkDigit;
The first line calls checkDigit but throws away the result.
The second line does not call the function, instead the compiler will let it decay to a pointer to the function and assign that pointer to itsdigit. Your compiler should have complained about it.
Furthermore, isdigit doesn't have to return 1 when the character is a digit, it only have to return something which is non-zero.
Lastly, in the digits array you don't store characters, you store integer values. isdigit(1) will be false while isdigit('1') will be true. Just because you use the type char doesn't automatically store characters in the variables. And considering that you read an integer, and store its digits in the digits array, there's no need to check if the digits are actually digits. Of course the digits will be digits.
You probably want this:
bool IsOnlyDigits(const char text[])
{
int length = strlen(text);
for (int i = 0; i < length; i++)
{
if (!isdigit(text[i]))
return false;
}
return true;
}
int main() {
char num[50];
scanf("%s", num);
if (IsOnlyDigits(num))
puts("It's digits!");
else
puts("It's not digits!");
fflush(stdout);
getchar();
return 0;
}
Disclaimer: non error checking and non bounds checking code. #includes omitted for brevity. Is has been tested under Visual Studio 2015 and seems to be working fine here.
Examples of input and output:
123
It's digits!
12a
It's not digits!
abc
It's not digits!
To understand this, you need to learn about strings and arrays. Just read the corrsponding chapters in your C textbook.
You could instead create an array of type char or int, iterate through the array and check if any character instance is a digit or not using the isdigit() function.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char arr[10];
cin>>arr;
for(int i=0;i<strlen(arr);i++){
if(isdigit(arr[i])){
cout<<arr[i]<<" is a digit\n";
}
else {
cout<<arr[i]<<" is not a digit\n";
}
}
return 0;
}

How do I increment letters in c++?

I'm creating a Caesar Cipher in c++ and i can't figure out how to increment a letter.
I need to increment the letter by 1 each time and return the next letter in the alphabet. Something like the following to add 1 to 'a' and return 'b'.
char letter[] = "a";
cout << letter[0] +1;
This snippet should get you started. letter is a char and not an array of chars nor a string.
The static_cast ensures the result of 'a' + 1 is treated as a char.
> cat caesar.cpp
#include <iostream>
int main()
{
char letter = 'a';
std::cout << static_cast<char>(letter + 1) << std::endl;
}
> g++ caesar.cpp -o caesar
> ./caesar
b
Watch out when you get to 'z' (or 'Z'!) and good luck!
It works as-is, but because the addition promotes the expression to int you want to cast it back to char again so that your IOStream renders it as a character rather than a number:
int main() {
char letter[] = "a";
cout << static_cast<char>(letter[0] + 1);
}
Output: b
Also add wrap-around logic (so that when letter[0] is z, you set to a rather than incrementing), and consider case.
You can use 'a'+((letter - 'a'+n)%26);
assuming after 'z' you need 'a' i.e. 'z'+1='a'
#include <iostream>
using namespace std;
int main()
{
char letter='z';
cout<<(char)('a' + ((letter - 'a' + 1) % 26));
return 0;
}
See this https://stackoverflow.com/a/6171969/8511215
Does letter++ work?
All in all char is a numeric type, so it will increment the ascii code.
But I believe it must be defined as char letter not an array. But beware of adding one to 'Z'. You will get '[' =P
#include <iostream>
int main () {
char a = 'a';
a++;
std::cout << a;
}
This seems to work well ;)
char letter = 'a';
cout << ++letter;
waleed#waleed-P17SM-A:~$ nano Good_morning_encryption.cpp
waleed#waleed-P17SM-A:~$ g++ Good_morning_encryption.cpp -o Good_morning_encryption.out
waleed#waleed-P17SM-A:~$ ./Good_morning_encryption.out
Enter your text:waleed
Encrypted text:
jnyrrq
waleed#waleed-P17SM-A:~$ cat Good_morning_encryption.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
//the string that holds the user input
string text;
//x for the first counter than makes it keeps looping until it encrypts the user input
//len holds the value (int) of the length of the user input ( including spaces)
int x, len;
//simple console output
cout << "Enter your text:";
//gets the user input ( including spaces and saves it to the variable text
getline(cin, text);
//give the variable len the value of the user input length
len = (int)text.length();
//counter that makes it keep looping until it "encrypts" all of the user input (that's why it keeps looping while its less than len
for(x = 0; x < len; x++) {
//checks each letts (and spaces) in the user input (x is the number of the offset keep in mind that it starts from 0 and for example text[x] if the user input was waleed would be w since its text[0]
if (isalpha(text[x])) {
//converts each letter to small letter ( even though it can be done another way by making the check like this if (text[x] =='z' || text[x] == 'Z')
text[x] = tolower(text[x]);
//another counter that loops 13 times
for (int counter = 0; counter < 13; counter++) {
//it checks if the letts text[x] is z and if it is it will make it a
if (text[x] == 'z') {
text[x] = 'a';
}
//if its not z it will keeps increamenting (using the loop 13 times)
else {
text[x]++;
}
}
}
}
//prints out the final value of text
cout << "Encrypted text:\n" << text << endl;
//return 0 (because the the main function is an int so it must return an integer value
return 0;
}
Note: this is called caeser cipher encryption it works like this :
ABCDEFGHIJKLMNOPQRSTUVWXYZ
NOPQRSTUVWXYZABCDEFGHIJKLM
so for example my name is waleed
it will be written as : JNYRRQ
so its simply add 13 letters to each letter
i hope that helped you
It works but don't forget that if you increment 'z' you need to get 'a' so maybe you should pass by a check function that output 'a' when you get 'z'.
cast letter[n] to byte* and increase its referenced value by 1.