Eul
Eul

Reputation: 52

Enquiry about Basic C++ Regarding Structs

I am creating a basic C++ code for my first school assignment that simply requires me to create a program that asks for a time in hours, minutes and seconds and converts how much time this is equivalent to in seconds; extremely basic.

I think the errors I am getting are because of my possible misuse of the struct function.

After getting the same error: "expected primary-expression before â.â token" after multiple trials of tweaks, I decided to try the code without struct; simply defining them with float h,m,s,et and calling them by that name: cin >> h >> m >> s;. And it works. This is why I think the error is with my use of the struct function.

Here is the short code:

#include <iostream>

using namespace std;

int main() {

struct time {
 int hour;
 int minute;
 int second;
 int elapsedTime;
};

cout << "Enter a Time in the Format: HH MM SS: ";

cin >> time.hour >> time.minute >> time.second;

time.elapsedTime = ((time.hour*360)+(time.minute*60)+time.second);

cout << "The Amount of Time Elasped is: " << time.elapsedTime << " seconds." << endl;

return 0;

}

The aforementioned error is in the code's 16th line 3 times and once in it's 20th line.

Another error in the 18th line is: "expected unqualified-id before â.â token".

Any help would be greatly appreciated. I refuse to look at the professor's posted answers yet.

Thank you for your time :)

Upvotes: 1

Views: 222

Answers (4)

micnyk
micnyk

Reputation: 746

There is 3600 seconds in one hour by the way

Upvotes: 0

Oswald
Oswald

Reputation: 31685

struct time is a data type. What you need is a variable of that type:

struct time t;

cin >> t.hour >> t.minute >> t.second;

Upvotes: 0

Pete Becker
Pete Becker

Reputation: 76498

You don't need a struct for this; just get the three components of the time in separate variables and do a little arithmetic. But if you really want to use a struct, keep in mind that the definition of a struct creates a new type. That part of your code is fine. Once you've done that, you need to create a variable of that type:

time data;

and then you can access the fields, as data.hour, data.minute, data.second.

Upvotes: 0

Constantinius
Constantinius

Reputation: 35089

With:

struct time {
 int hour;
 int minute;
 int second;
 int elapsedTime;
};

you just declared the structure of your struct. You have to instantiate an instance of it:

time mytime;
cin >> mytime.hour;
cin >> mytime.minute;
cin >> mytime.second;

Upvotes: 3

Related Questions