Home > front end >  How to access both string and int values from a function in a class in C ?
How to access both string and int values from a function in a class in C ?

Time:02-02

#include <bits/stdc  .h>
using namespace std;

class animal { // class

public:
void get_data(string breed, string color, char gender, int age, int cost) {
    cout << "Breed:" << breed << "\n" << "Color:" << color << "\n" << "Gender:" << gender << "\n" << "Age:" << age << "\n" << "Cost:" << cost << "\n";
    }
} dog, cat; // object

int main()
{   
dog.get_data('Chihuahua', 'Brown', 'F', 5, 10000);
cat.get_data('British Shorthair', 'Gray', 'F', 3, 15000);
return 0;
}

Output should be Breed: Chihuahua Color: Brown .... etc.

This code is executing perfectly if I remove the string variables and values.

CodePudding user response:

You are mixing single quotes '' and double quotes "".

Unlike other languages, C and C treat them differently.

Single quotes are single characters only; double quotes define character arrays (aka C-strings).

To be honest, I'm surprised your code compiles. Usually the compiler tells you, that you cannot define string literals with single quotes.

CodePudding user response:

C uses " as a string delimiter and ' as a char delimiter. Your compiler should warn you that 'Chihuahua' is surely not correct string. Fix it to "Chihuahua" and the code should work!

  •  Tags:  
  • Related