I am learning how to create struct's and I am stuck on a program I made. Everything works fine until I try to input "2". When the program prints the symbol it's supposed to be "He" but prints "HeHelium" instead. I can't figure out what's wrong and why it's printing he.symbol
and he.name
all in one line. Link to image below.
#include <stdio.h>
#include <stdlib.h>
struct Element {
int num;
double mass;
char symbol[2];
char name[20];
};
int main()
{
struct Element h;
h.num = 1;
h.mass = 1.008;
strcpy(h.symbol, "H");
strcpy(h.name, "Hydrogen");
struct Element he;
he.num = 2;
he.mass = 4.0026;
strcpy(he.symbol, "He");
strcpy(he.name, "Helium");
int number;
printf("Please enter the number of the element you want info on. \n");
scanf("%d", &number);
if (number == 1 /*&& !(number > 1)*/) {
printf("Atomic Number: %d \n", h.num);
printf("Atomic Mass: %.3f \n", h.mass);
printf("Atomic Symbol: %s \n", h.symbol);
printf("Atomic Name: %s \n", h.name);
} else if (number == 2) {
printf("Atomic Number: %d \n", he.num);
printf("Atomic Mass: %.3f \n", he.mass);
printf("Atomic Symbol: %s \n", he.symbol);
printf("Atomic Name: %s \n", he.name);
} else {
printf("Invalid number! \n");
printf("Or that element hasn't been added to the date base yet. \n");
printf("Try back later \n");
}
return 0;
}
When I input "2":
You have assigned
Element.symbol
with only 2byte which can only store string with only one character as the other character will be used for null character. You should write "symbol[3]
" as the symbol of elements in periodic table are no longer than 2 characters. Also, your code can become quite messy if you want to assign values for all 118 elements. You can write your code like below: