how would I put this in a function?

I am not sure how i would put this code in a function. We were just introduced to functions in class this week and it's confusing. Thanks in advance!

#include <iostream>
#include <string>

using namespace std;

int getAverage(int);

int main (){
int grade;
string lastName, firstName;

int average = getAverage(grade);

cout << "Enter last name: ";
cin >> lastName;

cout << "Enter first name: ";
cin >> firstName;




cout << lastName << ", " << firstName << ": " << average;
}
int getsAverage (int avg){
int average;
int midterm, final;

average = ((midterm + final) / 2);
cout << "Enter midterm: ";
cin >> midterm;

cout << "Enter final: ";
cin >> final;
return average;
}
You already have it right. but average = ((midterm + final) / 2); should be just before return average; so the average is calculated with the values from the user, and not 0 (or whatever they were initialized to)

Also, you cannot use cin on strings. Use getline(cin, stringname); instead.
Last edited on
Also, you cannot use cin on strings.

sure you can.

this works just fine for me:
1
2
3
4
5
6
7
8
9
10
int main () {
    string s;
    cout << "enter a string: ";
    cin >> s;
    cin.ignore();
    cout << s;
    
    getchar();
    return 0;
}


i guess if the first name or last name have spaces in it, you would need getline, but you can use cin just like you could with c-strings. unless it's compiler dependent or something
Last edited on
Oh, I was unaware of that. I just like getline() better because it is much more versatile.
I just like getline() better because it is much more versatile.

Huh? Not really. You use the two for different things, the >> operator to get the next word (seperated by whitespace) and getline to get an entire line.
Yes, but you can specify a deliminator for getline(). If you wanted, the deliminator could be a space, or anything else you need really.
Topic archived. No new replies allowed.