0

Whats wrong with the code?

using namespace std; #include <iostream> #include <string> #include <cstdio> class classroom{ public: int roll_no; string gender; string name; string studentgender; if (gender == 'male'){ studentgender = 'he'; } else if (gender == 'female'){ studentgender = 'she' } void getinfo(int roll, string n){ roll_no = roll; name = n; } void showinfo(){ printf("the name of the student is %s and %s roll no is %i", name, studentgender roll_no); } }; int main() { classroom student1; student1.name = "sai"; student1.roll_no = 20; student1.showinfo(); } this code is written in c++ and I used printf instead of cout. even printf function works in some situations.But anyways can anyone tell me the correct code

14th Oct 2018, 2:24 PM
Sainath Dora
3 odpowiedzi
+ 2
1. when you compare string write it in the double quotes like "male" instead of 'male'. 2.you never assign value to gender. 3.you can only write if else statement in the fuction which you have directly written in the class. 4.%s in printf is used for char* type of arg. Here is fixed code... using namespace std; #include <iostream> #include <string> #include <cstdio> class classroom{ public: int roll_no; string gender; string name; string studentgender; void getinfo(int roll, string n,string gen){ roll_no = roll; name = n; gender = gen; if (gender == "male"){ studentgender = "his"; } else if (gender == "female"){ studentgender = "her"; } } void showinfo(){ //since you want to printf you need to convert to char array by c_str(). printf("the name of the student is %s and %s roll no is %i", name.c_str(), studentgender.c_str(), roll_no); } }; int main() { classroom student1; student1.getinfo(20,"Sai","male"); student1.showinfo(); }
14th Oct 2018, 8:20 PM
Tanay
Tanay - avatar
+ 1
yeah sure, c_str converts std::string to c style string that we usually create as char*.
15th Oct 2018, 6:29 AM
Tanay
Tanay - avatar
0
can you explain me c_str() ?
15th Oct 2018, 2:32 AM
Sainath Dora