brisk172 brisk172 - 2 months ago 12
C++ Question

C++ getline error

I'm getting this error and I can't figure it out.

no instance of overloaded function "getline" matches the argument list
argument types are: (std::istream, MyEnum)

enum MyEnum // Needs to be before the struct that uses it
{
Dog, Cat, Fish, Squirrel
};
struct MyStruct
{
int a;
float b;
string c;
MyEnum d;
};
int main()
{
char myCString[arraySize] = { 0 };
char myOtherCString[] = { "Yet another string" };
int myInt[4] = { 27, 39, 0, 42 };
string myString;
MyStruct aStruct = { 4, 3.5, "Dogs", Dog };
int x;
int * pX = &x;
array <MyStruct, arraySize> Animals;
// Storing values in uninitialized variables
myCString[0] = 'A';
myString = "A third string";
x = 4;
for (int i = 0; i < arraySize; i++)
{
Animals[i].a = rand() % 10;
Animals[i].b = rand() % 100 / 100.0;
Animals[i].c = MyEnum(rand() % 4);
cout << "Enter a name: ";
getline(cin, Animals[i].d);
}

Answer

You probably want to get input in Animals[i].c, because c is the string, and d is not.

Also, you probably want to assign MyEnum(rand() % 4); to Animals[i].d

for (int i = 0; i < arraySize; i++)
{
    Animals[i].a = rand() % 10;
    Animals[i].b = rand() % 100 / 100.0;
    Animals[i].c = MyEnum(rand() % 4);
    //        ^^^
    // Change it to Animals[i].d
    cout << "Enter a name: ";
    getline(cin, Animals[i].d);
    //                     ^^^
    // Change it to Animals[i].c
}

It's just a bad naming style, you should have some meaningful names for variables, with some meaningful names, you'll probably never have this kind of errors.

Comments