Walker Hunt
Walker Hunt

Reputation: 3

How to make a struct type array in C++

I want to make a program that will store the data from the Periodic Table of Elements into an array that I can access whenever I want. I want to do it by making a struct with the data for each element in it, and make an instance of that struct for each element in an array "periodicTable[119]"

Here is my code:

#include <iostream>
using namespace std;

struct element
{
    string symbol;
    string name;
    float atomicWeight;

};

element periodicTable[119];
periodicTable[1].symbol = "H";
periodicTable[1].name = "Hydrogen";
periodicTable[1].atomicWeight = 1.008;

int main()
{
    cout << periodicTable[1].symbol << periodicTable[1].name << periodicTable[1].atomicWeight << endl;

    return 0;
}

I run linux, and when I try to compile this I get this error: 'error: periodicTable does not have a type'

I would like to know how to make an array of structs correctly, and if anyone has a better way to make a program like this or see any other errors by all means let me know.

Upvotes: 0

Views: 310

Answers (2)

Yves
Yves

Reputation: 12371

Using global variables is not a good idea except that you have a strong reason. So normally you can do as below:

int main()
{
    element periodicTable[119];
    periodicTable[1].symbol = "H";
    periodicTable[1].name = "Hydrogen";
    periodicTable[1].atomicWeight = 1.008;
    cout << periodicTable[1].symbol << periodicTable[1].name << periodicTable[1].atomicWeight << endl;

    return 0;
}

If you really want to use the global variable, you can do like this:

#include <iostream>
using namespace std;

struct element
{
    string symbol;
    string name;
    float atomicWeight;

};

element periodicTable[119]{
    {},
    {"H", "Hydrogen", 1.008f},   // 1.008 is double, 1.008f is float
};

int main()
{
    cout << periodicTable[1].symbol << periodicTable[1].name << periodicTable[1].atomicWeight << endl;

    return 0;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You cannot use assignments (or any other statements, for that matter) outside of functions. Use initializers instead:

element periodicTable[119] = {
    {"H",  "Hydrogen", 1.008}
,   {"He", "Helium",   4.003}
,   ...
};

Also note that C++ arrays are indexed starting from zero, not from one, so the initial element of the array is periodicTable[0], not periodicTable[1].

Upvotes: 2

Related Questions