Struct Functions

Hey all, needing a little guidance here. SO were supposed to use 2 functions. One funtion to take input, and return a struct datatype. And one function to output.

I feel I'm just about there but I feel I'm not calling the output function correctly, as I seem to be getting garbage outputs before and after the correct output. I appreciate your input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  #include <iostream>
#include <cmath>
using namespace std;
//Structure Definition
struct Vehicles
{
    string car_model;
    string car_make;
    int mileage;
    int year;
};

Vehicles input(string carModel, string carMake, int mileage, int year);

void output(Vehicles var[], int size);

int main()
{
    Vehicles car[5];
    string carModel;
    string carMake;
    int mileage;
    int year;

for(int i = 1; i < 3; i++)  
{
  cout << "Input the Car Model for Car Number " << i << " ";
  cin >> carModel;
 cout << "Input the Car  Make ";
  cin >> carMake;
  cout << "Input the Car mileage ";
  cin >> mileage;
  cout << "Input the Car year ";
  cin >> year;

  car[i] = input(carModel, carMake, mileage, year);


}
output(car,5);
    return 0;
}


sample run:
Input the Car Model for Car Number 1 WRX
Input the Car Make Subaru
Input the Car mileage 122654
Input the Car year 2011
Input the Car Model for Car Number 2 Civic
Input the Car Make Honda
Input the Car mileage 326654
Input the Car year 1997




6

16

WRX

Subaru

122654

2011

Civic

Honda

326654

1997





1871686278

32761





4207320

0
Last edited on
Hi,

On line 25, your input starts at 1 and ends at 3. The array starts at 0 and ends 4. So your output function is trying to print values from car[0] and car[4] which weren't initialised, so it prints garbage.

Try to avoid magic numbers like 5. make them a constexpr variable instead. That way you can change the value in 1 place.

The output function could do with some text to explain which fields the values belong to.
Registered users can post here. Sign in or register to post.