Reputation: 61
All I simply want to do is a make a record that starts with C or D randomly and has a number along with it 1-10. so a record would be C10. Can anyone tell me what I am doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
/*
*
*/
int main(int argc, char** argv)
{
char letter[] = { 'C', 'D' };
char record[2];
int r=1;
while (r < 11)
{
char num;
num = r;
record = (letter[rand()%2],num);
r++;
}
return 0;
}
Upvotes: 0
Views: 142
Reputation: 4780
You want the characters '0'-'9' popping up, but you are assigning the character r a numerical value between 0 and 10. Check out the table of ASCII characters.
I'd try it like this:
char record[4];
for (unsigned r = 0; r <= 10; ++r) {
snprintf(record, sizeof(record), "%c%d", letter[rand() % 2], r);
}
Upvotes: 2
Reputation: 490028
For one obvious point, "C10" requires 4 characters, assuming you want it as a normal C string (3 in the string + 1 NUL terminator) but you've only made room for 2.
At least assuming you want your 1-10 as text characters, you'd typically want to do something like:
sprintf(record, "%c%d", letter[rand()%2], num);
Not that it matters a lot, but you seem to be including a lot of unnecessary headers for what you're doing.
Upvotes: 3
Reputation: 4514
record = (letter[rand()%2],num);
This is not a legal opporation... try this:
record[0] = letter[rand()%2];
record[1] = num;
Upvotes: 2