Do this code cannot be running? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Do this code cannot be running?

class Student { public: char name[100]; char number[20]; Student(char inputName, char inputNumber){ name[100] = inputName; number[20] = inputNumber; cout << name[100]; cout << number[20]; } }; int main(){ char nama[100], nomor[20]; cout << "Name : "; cin >> nama[100]; cout << "Number : "; cin >> nomor[20]; Student data(nama[100], nomor[20]); return 0; } Note : I have tried, but can only enter input for name only, number input cannot. Though I want to make an input name and number then the input results are displayed as output. Is the code above wrong? https://code.sololearn.com/cggQ5crBe4qh/?ref=app

11th Jan 2020, 11:56 AM
Vivian Azalia
Vivian Azalia - avatar
4 Answers
+ 5
Your program has some problems. First of all, it is not exactly neccessary to give the array size every time you use it, you only need to specify it at declaration time, afterwards using the identifier is sufficient. Then, the constructor of student accepts two single characters, where it should accept strings. Arrays decay to pointers anyway, so you should pass both parameters as const char*. Also, assigning C-strings doesn't work through the assignment operator, you have to use strcpy() when copying strings: https://en.cppreference.com/w/c/string/byte/strcpy When fixing all of those, it could look something like the following: https://code.sololearn.com/c9SXr7SJm4X7/?ref=app But honestly, you could save yourself a lot of trouble by simply using C++-strings instead of C-strings, as the class will handle all the nasty stuff for you: https://en.cppreference.com/w/cpp/string/basic_string
11th Jan 2020, 12:55 PM
Shadow
Shadow - avatar
0
You declared a variable "number" but try to cin "nomor". Looks like a spelling mistake Sorry, two different things. My bad
11th Jan 2020, 12:04 PM
TobCoder
0
I Initialized "nomor" in main and "number" in class Student. Does the naming need to be the same in class and in main function?
11th Jan 2020, 12:10 PM
Vivian Azalia
Vivian Azalia - avatar
0
Shadow thanks for your explanation 🙏
12th Jan 2020, 2:41 PM
Vivian Azalia
Vivian Azalia - avatar