-3

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.

Community
  • 1
  • 1
Newokmyne
  • 65
  • 2
  • 10

1 Answers1

-1

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;
}
Tu Bui
  • 1,660
  • 5
  • 26
  • 39
  • What's the point of casting `(int)(122 - 97 + 1)`? (also why aren't you just using the actual result of this calculation?) – UnholySheep Dec 20 '16 at 14:11
  • @UnholySheep It demonstrates the range [97,122] that the random number will be generated, as requested by the OP. U can replace it by the actual value of 26 but the readers may not understand where that number comes from. – Tu Bui Dec 20 '16 at 14:15
  • The cast is still pointless (and not even "proper" C++, use `static_cast` instead) – UnholySheep Dec 20 '16 at 14:16
  • the range is between 97 and 122m so why do I get uppercase letter or '.', '^', and some other special char? – Newokmyne Dec 20 '16 at 14:24
  • @Newokmyne : it is because you forgot the parenthesis around (122-97+1) – Tu Bui Dec 20 '16 at 14:38
  • @UnholySheep: u r rite. We don't need that cast. Code updated. – Tu Bui Dec 20 '16 at 14:41
  • Ah yes right... Thank you ^^ (I upvoted your reply by the way) – Newokmyne Dec 20 '16 at 14:43