Easy tutorial for C / C ++ - struct 1
struct
:
- A datatype can be provided by the compiler or it can be
defined by a user. A user-defined type can be defined as 'struct' to help you
define it. A new data type defined using 'struct' is called a struct.
- To declare a struct:
struct 'struct name' {
'Data type' 'member
variable 1';
'Data type' 'member variable 2';
'Data type' 'member variable 3';
...
};
'Data type' 'member variable 2';
'Data type' 'member variable 3';
...
};
'Struct name' : Indicates the name of the struct to be
used.
'Data type' 'member variable' : Declaration of the member
variables of the struct, same as general variable declaration. However, the
initial value can not be given because it only tells the struct that composes
the data type.
- To declare a struct variable for a new data type, of
course, the struct must be declared before declaration of the struct variables.
a) struct 'struct name' 'struct variable' (C language, C
++ language)
b) 'struct name' 'struct variable' (C ++ language)
- In C, the new data type 'struct name' must be prefixed with struct.
- To use member variables of a struct, use the following
dot operator.
'Structure name'.'Struct variable'
- You can use the dot operator to store data in member
variables or use member variables. Let's look at an example.
Example Code
#include
<iostream>
using
namespace std;
struct
t_Struct{
int num;
char fruit[30];
char color[30];
};
int
main() {
t_Struct strA;
cout << " Insert number =
" ;
cin
>> strA.num ;
cout << " Insert fruit = " ;
cin
>> strA.fruit ;
cout << " Insert color = " ;
cin
>> strA.color ;
cout << endl;
cout << "*** Print results
***" << endl;
cout << " number = " <<
strA.num << endl ;
cout << " fruit = " << strA.fruit << endl ;
cout << " color = " << strA.color << endl ;
return 0;
}
- We have declared a struct named 'strA'. And we have
defined the integer variable 'num', the string variables 'fruit' and 'color' as
member variables.
- We have declared the struct variable 'strA' in the main
function. And we saved the data to each member variable through keyboard input.
(ex: "cin >> strA.num;")
- We have also written the syntax to output the input data.
results :
Insert
number = 10
Insert fruit
= banana
Insert color
= blue
- You will be asked to enter numbers, fruits and colors.
Type 10, banana, blue in turn, and hit Enter.
Insert
number = 10
Insert fruit
= banana
Insert color
= blue
***
Print results ***
number = 10
fruit =
banana
color =
blue
- You can
see that the input result is printed.
No comments:
Post a Comment