char question

i have a question about the rand() function say i want to read two character in like AB or and WC

im trying to do it in a character array but when i cout it just print the W last even thought it suppose to be first and doesnt even show C
Show the relevant code. Otherwise we will not be able to tell what's wrong.
I think you misunderstand sth. rand() will give you a random number, but doesn't get you any input.
To input two chars into a char array do it like this.
1
2
3
4
5
6
  char input[3] = {0};

  cout << "Enter two characters: ";
  cin.getline(input, sizeof(input));

  cout << "Your input was " << input << "\n\n";
alright so i have two question im going to show the code for the first question i have
first im trying to generate a random string between 6-14 it only give me 8
1
2
3
4
5
6
7
8
char alphabet[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string name;
 for(int i=6; i<14; i++)//this loop the letter between 6-14 and it only give me 8
           {
             random = alphabet[rand()%26];// i try doing something here it doesnt work  
              name +=random;                      //it picks from the alphabet randomly
           }
         cout << name

Next, question
so im not sure how to set this up so when i cout right it doesnt print the way i wanted it too
1
2
3
char color[]={'TH','MA','\0'};
b=color[rand()%2];
cout << b

when i cout i only get a 'H' but never a 'TH' together and sometimes the A will put up but not the 'MA'
im not sure if im formatting it correctly i think i need a for loop
Last edited on
The loop starts from 6 and stops at 14. 14 - 6 = 8, so that means it will run 8 times. If you want the loop to run 6-14 times you need to first generate a random number in that range. Then you can simply write the loop so that it starts from 0 and stops when it reaches the random number that you generated before loop.

A char can only hold one character. If you want multiple characters you'll have to use strings.
Last edited on
does it need to be before the for loop
If you do it after the loop you can't use it to decide when to stop the loop, so I guess you would have to always generate a string of length 14 and then remove 0-8 characters after the loop.
in order to generate 6-14 it needs to be rand()%9+8
The correct formula is: rand() % (max - min + 1) + min
When min=6 and max=14 it becomes: rand() % 9 + 6
i already solve it and i got to work in the loop thank for the help
Topic archived. No new replies allowed.