I am a real c++ beginner and I have a problem with my char array output in a c++ excerise. I was asked to transform a certain UML class in to c++ and generate an working output with the parameters given in main. Here ist the code:
#include <iostream> #include <stdlib.h> /*My class defintion book*/ class Book { protected: long int number; char author[25]; int year; bool lent; void setLent(bool x); bool getLent(); public: Book(long int n, char a[25], int j, bool x); long int getNr(); int getYear(); void print(); }; /*Method definition Book*/ Book::Book(long int n, char a[25], int j, bool x) {number=n; author=a; year=j; lent=x;} long int Book::getNr() {return number; } int Book::getYear() {return year;} void Book::setLent(bool x) {lent=x;} bool Book::getLent() {return lent;} void Book::print() { std::cout << "Book Nr: " << number << std::endl; std::cout << "Author: " << author << std::endl; std::cout << "Year: " << year << std::endl; if (lent==0) std::cout << "Lent [yes/no]: no" << std::endl; else std::cout << "Lent [yes/no]: yes" << std::endl; } /*MAIN*/ int main() { Book b1(123456, "test", 2014, false); b1.print(); system("pause"); return 0; This is my output:
Book Nr: 123456 Author: b<Vv-[[vóYA Year: 2014 Lent [yes/no]: no Press any key to continue... As you can see all outputs work except for the "Author". There I am getting crap. Note that I have to use char as type. since it is given in the UML class I had to transform into c++.
I really searched everywhere. But didn't find the correct solution. I have the feeling it will be a very simple one...
Thanks in advance for your help!
author=a;<-- this line in your constructor doesn't do what you think it does. Why aren't you usingstd::string?