I am trying to convert an int to a char using the ASCII value. The int is randomly generated between 97 and 122 (from a to z).
How can I generate a random number between 97 and 122 and convert it to a char?
I searched many answers before asking my question, but none solved the problem or was completely related to my need. Even this didn't work.
Here is what I'm trying to do: in a for loop, the program generates a random number and converts it to an int. This is converted to its ASCII value and then placed into a QString. When the for loop is finished, I send the QString to a line_edit.
By following the above link, I only got an m.
Here's my code:
QString str;
int maxlenght = 16; //the user will be able to set himself the maxlenght
for (int i =0; i<maxlenght; i++)
{
int random = 97 + (rand() % (int)122-97+1);
char letter = (char)random;
if(i > 0)
{
str[i] = letter;
}
}
And though the random number is generated in the loop, it always gives me the same char.
You need to convert string to QString after that.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string str="";
int maxlenght = 16; //the user will be able to set himself the maxlenght
for (int i =0; i<maxlenght; i++)
{
int rand_num = 97 + (rand() % (122 - 97 + 1));
char letter = static_cast<char>(rand_num);
str += letter;
}
cout << str << endl;
return 0;
}
Related
When I try to compile my code this error pops out:
invalid conversion from 'int' to 'const char*'
My task is to write a program that calculates the sum of numbers with odd index.
Please don't roast me (I'm learning how to code in c++), and give some tips how to fix it and get my code working.
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = len; i > 0; i++) {
a = text[i];
if (i % 2 == 1) {
number = atoi(a);
sum = sum + number;
}
}
cout << sum;
return 0;
}
Your for loop is incorrect because at the first try it starts at out of range index and increases farther. here :
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = 0; i < len; i++) {
a = text[i];
if (i % 2 == 1) {
number = a - '0';
sum = sum + number;
}
}
cout << sum;
return 0;
}
atoi is a function for converting a string to an integer, but a is a character not a string. That's why you have the error.
Replace atoi(a); with a - '0'. That's a formula for converting a digit character to its integer value.
I see a few issues. The most obvious:
number = atoi(a);
atoi expects a const char *, but a is an int.
Note that it would help if you listed which line produces the error message.
Without trying it, I think you can get rid of the atoi() and just do:
sum += a - '0';
The other choice would be to make a into a string and use text.subst() to just get a single character, then you could do:
sum += atoi (a.c_str());
or
sum += stoi(a);
In programming, there are always a dozen of ways to do the same thing.
Learn to extract functions. This will do your task without converting to string.
int sumOfDigitsInEvenPos(int x, int base = 10) {
x = std::abs(x);
int sum = 0;
while (x) {
sum += x % base;
x /= base * base;
}
return sum;
}
There are more than few mistakes :
starting with declaring 'a' as int.
in Your for loop you are starting with length which should be
length-1.
In for loop again you are using i++ which should be i-- or start with i=0;
When you are getting number why you are taking string as input
taking as int/long should be more convient.
atoi accepts char * not int
try out below code it should solve your problem
#include <bits/stdc++.h>
#include <cmath>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
cin>>text;
int len= text.length();
cout<<len<<endl;
int sum=0,number=0;
char a;
for(int i=len-1;i>0;i--)
{
a=text[i];
if(i%2==1)
{ number= (int)a;
sum = sum+number;
}
}
cout<<sum;
return 0;
}
I think you need to check return code of atoi function, because string consists non only of numeric values.
And length returns size of string, for example 5, but symbols iterates from 0 to 4. text[4] - final symbol.
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;
}
This function is meant to remove all special characters, numbers, and whitespace from the char array.
// Michael E. Torres II
// Vigenere Cipher
// February 4, 2018
// C++ code to implement Vigenere Cipher
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <iterator>
#include <sstream>
#include <functional>
using namespace std;
// This function generates the key in
// a cyclic manner until it's length isi'nt
// equal to the length of original text
string generateKey(string str, string key)
{
int x = str.size();
for (int i = 0; ; i++)
{
if (x == i)
i = 0;
if (key.size() == str.size())
break;
key.push_back(key[i]);
}
return key;
}
// This function returns the encrypted text
// generated with the help of the key
string cipherText(string str, string key)
{
string cipher_text;
for (int i = 0; i < str.size(); i++)
{
// converting in range 0-25
int x = (str[i] + key[i]) % 26;
// convert into alphabets(ASCII)
x += 'A';
cipher_text.push_back(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
string originalText(string cipher_text, string key)
{
string orig_text;
for (int i = 0; i < cipher_text.size(); i++)
{
// converting in range 0-25
int x = (cipher_text[i] - key[i] + 26) % 26;
// convert into alphabets(ASCII)
x += 'A';
orig_text.push_back(x);
transform(orig_text.begin(), orig_text.end(), orig_text.begin(), ::tolower);
}
return orig_text;
}
string removeNonAlpha(char *str)
{
unsigned long i = 0;
unsigned long j = 0;
char c;
while ((c = str[i++]) != '\0')
{
if (isalpha(c)) // this is where the breakpoint is automatically placed
{
str[j++] = c;
}
}
str[j] = '\0';
return str;
}
// Driver program to test the above function
int main(int argc, char *argv[])
{
string keyword = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
stringstream ss;
char a[] = "“I think and think for months and years. Ninety-nine times, the conclusion is false. The hundredth time I am right.” – Albert Einstein “Imagination is more important than knowledge. For knowledge is limited, whereas imagination embraces the entire world, stimulating progress, giving birth to evolution.” – Albert Einstein";
int i = 0;
string str = removeNonAlpha(a);
str.append(512 - str.length(), 'X');
transform(str.begin(), str.end(), str.begin(), ::toupper);
transform(keyword.begin(), keyword.end(), keyword.begin(), ::toupper);
string key = generateKey(str, keyword);
string cipher_text = cipherText(str, key);
transform(cipher_text.begin(), cipher_text.end(), cipher_text.begin(), ::tolower);
transform(key.begin(), key.end(), key.begin(), ::tolower);
string orig = originalText(cipher_text, key);
cout << "Original/Decrypted Text : " << "\n";
for (int i = 0; i < orig.size(); i += 81)
orig.insert(i, "\n");
cout << orig;
cout << "\n\n" << "Ciphertext : " << "\n";
for (int i = 0; i < cipher_text.size(); i += 81)
cipher_text.insert(i, "\n");
cout << cipher_text;
cout << "\n\nPress ENTER key to Continue\n";
getchar();
return 0;
}
The char array works fine with this while loop, so long as there are no special characters [.,%$#!^]. As soon as there are any special characters in the char array, it gives me the debug assertion:
"Program: ...\Projects\ConsoleApplication17\Debug\ConsoleApplication17.exe
File: minkernel\crts\ucrt\src\appcrt\convert\isctype.cpp
Line: 42
Expression: c >= -1 && c <= 255
...
The program '[11048] ConsoleApplication17.exe' has exited with code 3 (0x3)."
If I run this on repl.it or cpp.sh, I get no issues though. I appreciate any help. Thank you.
It isn't done at all. It needs to be cleaned up a lot, but I'm just trying to test it as is.
see https://msdn.microsoft.com/en-us/library/xt82b8z8.aspx
isalpha expects a number between 0 and 0xFF:
The behavior of isalpha and _isalpha_l is undefined if c is not EOF or
in the range 0 through 0xFF, inclusive. When a debug CRT library is
used and c is not one of these values, the functions raise an
assertion.
You need to cast you char to an unsigned char before passing to isalpha.
First time on stack overflow.
I have this assignment due for class where we have a guessing game where our program has to generate a string of Uppercase letters of n length and n different defined by the user. I got most of my assignment working but when generate the string I am lost with how I could put these conditions in place for it to work.
char create_sequence(){
return rand() % 26 + 65;
}
Do you have any tips?
If you know sequence length, you don't need amount of different characters. This is because you require length <= characters.
To create sequence of n unique characters write a separate function:
vector<char> create_sequence(int n) {
vector<char> letters;
for (char ch = 'A'; ch <= 'Z'; ++ch) {
letters.push_back(ch);
}
vector<char> sequence;
for (int i = 0; i < n; ++i) {
int index = rand() % letters.size();
sequence.push_back(letters[index]);
letters.erase(letters.begin() + index, letters.begin() + index + 1);
}
return sequence;
}
Well, personally I think you are not far from the answer:
rand() % 26 + 65
Will effectively returns an uppercase ASCII letter. As long as you initialize the random seed once srand (time(NULL));, you can then call your instruction as many times as you want to get random values. So all you miss is a simple loop. Here is an example for 5 characters:
#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
char randomChar(){
return rand() % 26 + 65;
}
std::string randomString(int length)
{
srand (time(NULL));
std::string rc("");
for(int i=0; i<length; ++i)
{
rc += randomChar();
}
return rc;
}
int main()
{
std::cout << "Random string (x5) is " << randomString(5) << "\n";
}
I understand that questions with this title/problem have been asked numerous times before (here,here and many others). Here is my code followed by what all I have done to remove the error:
CaesarCipher.h
#ifndef CAESARCIPHER_H
#define CAESARCIPHER_H
#include <ctime>
#include <string>
using namespace std;
// Write your class CaesarCipher here.
class CaesarCipher
{
public:
CaesarCipher();
string Encode(string plainString);
string Decode(string encryptedString);
private:
int key1, key2;
char Encode(char normalChar)const;
char Decode(char encodedChar)const;
};
#endif
CaesarCipher.cpp
#include "stdafx.h"
#include "CaesarCipher.h"
using namespace std;
// Implement the member functions of class CaesarCipher.
CaesarCipher::CaesarCipher()
{
//Random initialization of integer key1
//srand(time(0));
srand((unsigned int)time(0));
int value1 = rand() % 10;
int sign1 = rand() % 2;
sign1 = sign1 == 0 ? -1 : 1;
int key1 = value1 * sign1;
//Random initialization of integer key2
//srand(time(0));
srand((unsigned int)time(0));
int value2 = rand() % 10;
int sign2 = rand() % 2;
sign2 = sign2 == 0 ? -1 : 1;
int key2 = value2 * sign2;
}
char CaesarCipher::Encode(char normalChar) const
{
int result=0;
int charValue = normalChar; //get the ASCII decimal value of character
if (charValue == 32) // if characeter is a space, we leave it
{
result = 32;
}
else
{
if (key1 > 0)
{
result = char(int(charValue + key1 - 97) % 26 + 97); // find the integer value of char after rotating it with key1(positive)
}
if (key1 < 0)
{
result = char(int(charValue -key1 - 97) % 26 + 97); // find the integer value of char after rotating it with key1(negative)
}
if (key2 > 0)
{
result += char(int(charValue + key2 - 97) % 26 + 97); // find the updated integer value of char after rotating it with key2(positive)
}
if (key2 < 0)
{
result += char(int(charValue - key2 - 97) % 26 + 97); // find the updated integer value of char after rotating it with key2(negative)
}
}
return result; // returning the integer value which will be typecasted into a char(encoded char)
}
char CaesarCipher::Decode(char encodedChar) const
{
int result = 0;
int charValue = encodedChar; //get the ASCII decimal value of encoded character
if (charValue == 32) // if characeter is a space, we leave it unchanged
{
result = 32;
}
else
{
if (key1 > 0)
{
result = char(int(charValue - key1 - 97) % 26 + 97); // find the integer value of encoded char after rotating it with key1(positive) in opposite direction
}
if (key1 < 0)
{
result = char(int(charValue + key1 - 97) % 26 + 97); // find the integer value of encoded char after rotating it with key1(negative) in opposite direction
}
if (key2 > 0)
{
result += char(int(charValue - key2 - 97) % 26 + 97); // find the updated integer value of encoded char after rotating it with key2(positive) in opposite direction
}
if (key2 < 0)
{
result += char(int(charValue + key2 - 97) % 26 + 97); // find the updated integer value of encoded char after rotating it with key2(negative) in opposite direction
}
}
return result; // returning the integer value which will be typecasted into a char(decrypted char)
}
string CaesarCipher::Encode(string plainString)
{
int length = plainString.length(); //gets the length of the
input string
string encodedString; // variable to hold the final encrypted string
for (int i = 0; i < length; i++)
{
encodedString[i] = Encode(plainString[i]); // encrypting the string one character at a time
}
return encodedString; // return the final encoded string
}
string CaesarCipher::Decode(string encryptedString)
{
int length = encryptedString.length(); //gets the length of the input encrypted string
string decodedString; // variable to hold the final decrypted string
for (int i = 0; i < length; i++)
{
decodedString[i] = Decode(encryptedString[i]); // decrypting the string one character at a time
}
return decodedString; // return the final decoded string
}
I am using two keys to cipher the text (key1 followed by key2), if it helps in any way.
Main.cpp
#include "stdafx.h"
#include "CaesarCipher.h"
#include <fstream>
#include <iostream>
int main() {
// File streams
ifstream fin("input.txt");
ofstream fout("output.txt");
if (!fin.good()) {
cout << "Error: file \"input.txt\" does not exist!" << endl;
return -1;
}
string original[20], encrypted[20], decrypted[20];
int i = 0; // will store the number of lines in the input file
CaesarCipher cipher; // an object of CaesarCipher class
// Read the sentences from the input file and save to original[20].
// Hint: use getline() function.
while (!fin.eof())
{
getline(fin, original[i]); // Reading a line from input.txt file
encrypted[i] = cipher.Encode(original[i]); // Encrypt the sentences and save to encrypted[20]
decrypted[i] = cipher.Decode(encrypted[i]); // Decrypt the sentences and save to decrypted[20]
i++;
}
//first output all the encrypted lines
for (int j = 0; j < i; j++)
{
fout << "Encrypted sentences:\n";
fout << encrypted[j]<<"\n";
}
//now output all the decrypted lines
for (int j = 0; j < i; j++)
{
fout << "Decrypted sentences:\n";
fout << decrypted[j] << "\n";
}
// Close the files and end the program.
fin.close();
fout.close();
cout << "done!";
return 0;
}
The error which i am getting isExpression: string subscript out of range. Now i understand that i am trying to iterate beyond the limits of the string (somewhere probably in CaesarCipher.cpp in Encoder or Decoder function).
I have tried to change the limits on i without any effect.
I have tried to use size() instead of length() (in desperacy inspite knowing they do the same thing).
I would really appreciate if you can pin-point any thing in particular which might be causing this error and i will try and change it by myself and see the results.
And if you can also tell, how to avoid such errors in future that will also be of great value to me.
CaesarCipher::Encode() is not allocating any memory for the character data of encodedString, so the loop has nothing valid to access with encodedString[i]. To fix that, either:
Use string encodedString = plainString; to make a copy of the input string, then the loop can manipulate the copied data:
string CaesarCipher::Encode(string plainString) {
int length = plainString.length(); //gets the length of the input string
string encodedString = plainString; // variable to hold the final encrypted string
for (int i = 0; i < length; i++) {
encodedString[i] = Encode(encodedString[i]); // encrypting the string one character at a time
}
return encodedString; // return the final encoded string
}
Use encodedString.resize(length) to pre-allocate the output string before entering the loop:
string CaesarCipher::Encode(string plainString) {
int length = plainString.length(); //gets the length of the input string
string encodedString; // variable to hold the final encrypted string
encodedString.resize(length); // allocate memory for the final encoded string
for (int i = 0; i < length; i++) {
encodedString[i] = Encode(plainString[i]); // encrypting the string one character at a time
}
return encodedString; // return the final encoded string
}
Use encodedString += plainString[i]; to append characters to the output string and let it grow as needed:
string CaesarCipher::Encode(string plainString) {
int length = plainString.length(); //gets the length of the input string
string encodedString; // variable to hold the final encrypted string
for (int i = 0; i < length; i++) {
encodedString += Encode(plainString[i]); // encrypting the string one character at a time
}
return encodedString; // return the final encoded string
}
The same problem exists in CaesarCipher::Decode() with the decodedString variable.
Also, main() has a buffer overflow if input.txt has more than 20 lines in it. Consider changing the code to use std::vector instead of fixed arrays.
And while (!fin.eof()) is wrong to use. Use while (getline(...)) instead:
// Read the sentences from the input file and save to original[20].
// Hint: use getline() function.
string line;
while (getline(fin, line)) { // Reading a line from input.txt file
original[i] = line;
encrypted[i] = cipher.Encode(original[i]); // Encrypt the sentences and save to encrypted[20]
decrypted[i] = cipher.Decode(encrypted[i]); // Decrypt the sentences and save to decrypted[20]
i++;
}