Brandon Benthal Brandon Benthal - 3 months ago 64
C++ Question

C++ getline won't work with int?

I've been working on this project for my C++ class in which I have to get a collection of information from the user, including the users birthyear and the current year (we have yet to learn how to access the computer's date so it has to be manually retrieved). I'm still fairly early in the process and I've run into this obstacle that I can't seem to work around.

While I've used this process to easily get the name system to work using the custom class, I can't get it to work for the year value. I can only assume the issue is that the year is an int rather than a string, but I can't possibly figure out any other way to get this to work. Could someone please look at this code and help me figure out what the issue is?

Main class:

#include <iostream>
#include <string>
#include "Heartrates.h"

using namespace std;

int main() {
Heartrates myHeartrate;
cout << "Please enter your name (First and Last): ";
string yourName;
getline (cin, yourName);
myHeartrate.setName(yourName);

cout << "\nPlease enter the current year: ";
int currentYear;
getline (cin, currentYear);
myHeartrate.setCyear(currentYear);


cout << "\nYou entered " << currentYear;
}


Heartrate class:

#include <string> //enables string use

class Heartrates {
public:
void setName(std::string yourName) {
name = yourName;
}

std::string getName() const {
return name;
}

void setCyear(int currentYear) {
Cyear = currentYear;
}

int getCyear() const {
return Cyear;
}

private:
std::string name;
int Cyear{ 0 };
};


I keep running into an error that states there is no matching overload function found, yet as you can see I'm using the same structure between both the main class and the header and the name worked just fine.

Answer

The version of std::getline you are trying to use there does not accept an int as a argument. See the function marked 2 (C++11) for the function you are trying to call here. std::istringstream can be included from sstream. I would add a std::endl (or new line) to the final print out to make it appear nicer as well.

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
    Heartrates myHeartrate;
    cout << "Please enter your name (First and Last): ";

    // read line
    string line;
    getline (cin, line);
    // line is yourName 
    myHeartrate.setName(line);
    // read line, read int from line
    cout << "\nPlease enter the current year: ";
    int currentYear;
    getline (cin, line);
    std::istringstream ss(line);
    ss >> currentYear;
    myHeartrate.setCyear(currentYear);

    cout << "\nYou entered " << currentYear << endl;
    return 0;
}