How to get an easier way of generating the alphabet in C++? - 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;
}

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 convert Int to String and vice versa in c++ (without using libraries like sstream)

For my university computer science course, our professor wants us to use a method of converting a string to an int (and int to string) without the use of any libraries such as sstream. I can't exactly find it anywhere in the notes/online and am hoping someone could show/tell me what it is and tell me how afterwards I would know that it has successfully been converted. All I know is that it involves using static_cast and also ASCII. He went over it quickly in class and I copied the code down quickly so there's a chance I could be missing something important or mistyped something, but here's what I got.
void intToStr(){
string numString = "2019";
int num = 0;
for(int i =0; i < numString.length(); i++){
char c = numString[i];
num = num * 10 + static_cast<int>(c) - static_cast<int>('0');
}
}
You don't have to create c as a char as that adds an extra step for conversion and can look overwhelming with static_cast
c++ will assign the ASCII value for a char if you assign it to an int so for example the char version of '2' has an ascii code of 50 to get it's integer value you subtract the char version of '0' as that is the first ascii value corresponding to digits, similarily if you want to get the number value of a letter say you're doing something like converting a string to a number you would first assign the letter to an int to get its ascii value and subtract the char 'a' or 'A' depending on what case you are working with and it would return that letters index in the alphabet, below is the code demonstrating what i'm taling about for numbers
// Example program
#include <iostream>
#include <string>
using namespace std;
int main(){
string numString = "2019";
int num = 0;
for(int i =0; i < numString.size(); i++){
int c = numString[i] -'0';
cout << c << endl;
num = num * 10 + c;
}
cout << num << endl;
}

C++ char array addition

So I recently started learning C++, been watching a lot of tutorials and stumbled upon a tricky question. I want to enter a max number n and enter two numbers stored in a char array. Then I would want to pass them into my add function to do simple addition. It would always return a letter though. I know it has to do with the char ASCII, but is there any way besides using strings to accomplish this?
#include <iostream>
using namespace std;
void add(char m1[], char m2[], int n);
int main()
{
int n = 0;
cin >> n;
const char CAPACITY = 100;
char m1[CAPACITY] = {0};
char m2[CAPACITY] = {0};
for(int i = 0; i < n; i++)
{
cin >> m1[i];
}
for(int i = 0; i < n; i++)
{
cin >> m2[i];
}
add(m1, m2, n);
}
void add(char m1[], char m2[], int n)
{
char sum[100] = {0};
for(int i = 0; i < n; i++)
{
sum[i] = m1[i] + m2[i];
}
for(int i = 0; i < n; i++)
cout << sum[i];
}
It's important to know the difference between '3' and 3. The first is a character, a symbol. The second is a number formed of one digit. In C++ unfortunately and confusing for beginners characters can sometimes appear to act as numbers. They are implicitly convertible to integers and operations like summing them are allowed, although it doesn't make any sense to add two symbols. When a character is acting up as a number its numeric value is the character representation code. I.e. each character has a code (or number) associated with it as part of the character encoding scheme. The most used character encoding scheme for char is ASCII.
When you do '3' + '0' you are actually adding the character codes. If you look in an ASCII table you will see that the code for '3' is 51 and the code for '0' is 48 so the result is 99. Due to the implicit (hidden) conversions happening in '3' + '0' the result (99) is of type int, not char.
More formally, '3' + '0' is equivalent to:
static_cast<int>('3') + static_cast<int>('0')
When you store the result (remembers the result it's an int) to a char (like you do in sum[i] = m1[i] + m2[i] then the integer is implicitly converted to a char. Again, if you look in the ASCII table you see that the code 99 corresponds to the character 'e'.
It helps a lot if you think of characters as symbols. There are alpha characters: 'a', 'b', etc.; digit characters: '0', '1', etc.; punctuation and whitespace characters: ' ', ';', '-' etc. and control characters: '\0' etc. It helps a lot if you think of all of them being in the same boat. It helps if you think as 'a' and '3' being both symbols, being of same type. Then you will see that '3' + '0' doesn't make sense any more than 'a' + 'b' makes sense.
I, but is there any way besides using strings to accomplish this?
You mean to add two numbers? Sure:
int a, b;
std::cin >> a >> b;
int sum = a + b;
std::cout << sum << std::endl;
Mind. Blown.

Comparing a char

So, I am trying to figure out the best/simplest way to do this. For my algorithms class we are supposed read in a string (containing up to 40 characters) from a file and use the first character of the string (data[1]...we are starting the array at 1 and wanting to use data[0] as something else later) as the number of rotations(up to 26) to rotate letters that follow (it's a Caesar cipher, basically).
An example of what we are trying to do is read in from a file something like : 2ABCD and output CDEF.
I've definitely made attempts, but I am just not sure how to compare the first letter in the array char[] to see which number, up to 26, it is. This is how I had it implemented (not the entire code, just the part that I'm having issues with):
int rotation = 0;
char data[41];
for(int i = 0; i < 41; i++)
{
data[i] = 0;
}
int j = 0;
while(!infile.eof())
{
infile >> data[j+1];
j++;
}
for(int i = 1; i < 27; i++)
{
if( i == data[1])
{
rotation = i;
cout << rotation;
}
}
My output is always 0 for rotation.
I'm sure the problem lies in the fact that I am trying to compare a char to a number and will probably have to convert to ascii? But I just wanted to ask and see if there was a better approach and get some pointers in the right direction, as I am pretty new to C++ syntax.
Thanks, as always.
Instead of formatted input, use unformatted input. Use
data[j+1] = infile.get();
instead of
infile >> data[j+1];
Also, the comparison of i to data[1] needs to be different.
for(int i = 1; i < 27; i++)
{
if( i == data[1]-'0')
// ^^^ need this to get the number 2 from the character '2'.
{
rotation = i;
std::cout << "Rotation: " << rotation << std::endl;
}
}
You can do this using modulo math, since characters can be treated as numbers.
Let's assume only uppercase letters (which makes the concept easier to understand).
Given:
static const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const std::string original_text = "MY DOG EATS HOMEWORK";
std::string encrypted_text;
The loop:
for (unsigned int i = 0; i < original_text.size(); ++i)
{
Let's convert the character in the string to a number:
char c = original_text[i];
unsigned int cypher_index = c - 'A';
The cypher_index now contains the alphabetic offset of the letter, e.g. 'A' has index of 0.
Next, we rotate the cypher_index by adding an offset and using modulo arithmetic to "circle around":
cypher_index += (rotation_character - 'A'); // Add in the offset.
cypher_index = cypher_index % sizeof(letters); // Wrap around.
Finally, the new, shifted, letter is created by looking up in the letters array and append to the encrypted string:
encrypted_text += letters[cypher_index];
} // End of for loop.
The modulo operation, using the % operator, is great for when a "wrap around" of indices is needed.
With some more arithmetic and arrays, the process can be expanded to handle all letters and also some symbols.
First of all you have to cast the data chars to int before comparing them, just put (int) before the element of the char array and you will be okay.
Second, keep in mind that the ASCII table doesn't start with letters. There are some funny symbols up until 60-so element. So when you make i to be equal to data[1] you are practically giving it a number way higher than 27 so the loop stops.
The ASCII integer value of uppercase letters ranges from 65 to 90. In C and its descendents, you can just use 'A' through 'Z' in your for loop:
change
for(int i = 1; i < 27; i++)
to
for(int i = 'A'; i <= 'Z'; i++)
and you'll be comparing uppercase values. The statement
cout << rotation;
will print the ASCII values read from infile.
How much of the standard library are you permitted to use? Something like this would likely work better:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
int rotation = 0;
std::string data;
std::stringstream ss( "2ABCD" );
ss >> rotation;
ss >> data;
for ( int i = 0; i < data.length(); i++ ) {
data[i] += rotation;
}
// C++11
// for ( auto& c : data ) {
// c += rotation;
// }
std::cout << data;
}
Live demo
I used a stringstream instead of a file stream for this example, so just replace ss with your infile. Also note that I didn't handle the wrap-around case (i.e., Z += 1 isn't going to give you A; you'll need to do some extra handling here), because I wanted to leave that to you :)
The reason your rotation is always 0 is because i is never == data[1]. ASCII character digits do not have the same underlying numeric value as their integer representations. For example, if data[1] is '5', it's integer value is actually 49. Hint: you'll need to know these values when handle the wrap-around case. Do a quick google for "ANSI character set" and you'll see all the different values.
Your determination of the rotation is also flawed in that you're only checking data[1]. What happens if you have a two-digit number, like 10?

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.