I want to read 15 numbers then convert them into letters, something like: 1 = A, 2 = B, 3 = C, 4 = D... I have this structure here:
struct Num {
int number;
char letter;
};
struct Num num[150];
and this to read the numbers:
void read_num() {
int i;
for (i = 0; i < 15; i++) {
printf("Insert number\n");
scanf("%d", &num[i].number);
fflush(stdin);
}
}
and now I need something to convert each number into a letter, I did create a huge function with twenty five if
but it doesn't seem to work.
BTW I only need to go to the number 25
so its A to Y in the alphabet.
The function that doesn't work is this:
void convert() {
int i, ii;
for (i = 0; i < 15; i++) {
if (num[i].number = 1){
num[i].letter = "A";
} else
if (num[i].number = 2) {
num[i].letter = "B";
} else
if (num[i].number = 3) {
num[i].letter = "C";
} else
if (num[i].number = 4) {
num[i].letter = "D";
} else
if (num[i].number = 5) {
num[i].letter = "E";
...
}
}
}
Im using Dev C++ in windows and C programming, I know this is a noob question but help please!
1) Don't ever use fflush(stdin)
, it's undefined behavior = the worst thing that can happen to you in C programming.
2) Use ==
for comparison, like so: if (num[i].number == 5)
.
3) "a"
is a string literal of type const char[2]
. You want a char
, which is enclosed in single quotes: 'a'
.
With that said, in pretty much every encoding used today, letters are arranged in lexicographic order, so you can just do num[i].letter = (char)(num[i].number + 'A' - 1)
, so long as you're sure num[i].number
is in the range you want. If not, you will need conditionals, but it would be better style to use a switch
construct, like so:
switch (num[i].number)
{
case 1:
num[i].letter = 'A';
break;
...
}
And by the way, please don't use Dev-C++, it's outdated and no longer maintained. You can either use Code::Blocks if you want to stay with MinGW, or you could use one of the community editions of Visual C++, which are free (and can also be used to compile C code).