OOP C++(constant char pointer)

Pages: 12
I have some problems with the const char error. Its comeout a segfault for the result, please help me with this. *authors input is more than one



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Book
{
private:
    char *title;
    char *authors;
    int publishingYear;

public:
    Book()
    {
        
    }

    Book(const char *title, const char *authors, int publishingYear)
    {
        
        *this->title=*title;
        *this->authors=*authors;
        this->publishingYear=publishingYear;
    }
    
    ~Book()
    {
       
    }
    
    friend class Printer;
};

class Printer
{
public:
    static void printBook(const Book book)
    {
        cout<<book.title<<endl;
        char *tmp= new char[100];
        tmp=book.authors;
        while (tmp!=NULL)
            cout<<tmp<<endl;
        delete tmp;
        cout<<book.publishingYear<<endl;
    }
};


//===========================================================================
Last edited on
qtngmin,
Do you mean a segmentation fault? If so, which one? There are several, 11 is a common one– it means your program is trying to access memory that it shouldn't.

Also–
PLEASE USE CODE TAGS (the <> formatting button to the right of this box), when posting code.

Along with the proper indenting, it makes it easier to read your code, and thus also easier to respond to your post.

Tutorials on how to use code tags:

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

I found the second link to be the most help.

Hint: You can hit "edit post", highlight your code and then press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the "preview" button at the bottom to see how it looks.


I will look at your code and see if I can find the problem. Try debugging it and see if you can find the issue with that.
Luck,
max

Edit:
Here is your code using code tags and better formatting:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Book
{
private:
	char *title;
	char *authors;
	int publishingYear;

public:
	Book ()
	{}

	Book (const char *title, const char *authors, int publishingYear)
	{
		*this -> title = *title;
		*this -> authors = *authors;
		this -> publishingYear = publishingYear;
	}

	~Book()
	{}

	friend class Printer;
};

class Printer
{
public:
	static void printBook (const Book book)
	{
		std::cout << book.title << std::endl;
		
		char *tmp = new char[100];
		
		tmp = book.authors;
		
		while (tmp != NULL)
		{
			std::cout << tmp << std::endl;
		}
		
		delete tmp;
		
		std::cout << book.publishingYear << std::endl;
	}
};
Last edited on
thanks for your reply. Im a vietnamese so its hard for me to understand, sorry if its border you . The input is here
Book book1("Giai tich 1", "Nguyen Dinh Huy, Nguyen Thi Xuan Anh", 2000);
Printer::printBook(book1);

output as it shoud be
Giai tich 1
Nguyen Dinh Huy
Nguyen Thi Xuan Anh
2000

and i got this message
***Error***
Segmentation fault (core dumped)
I cant see where the error is because it is online submit, and i compile it online too
Ok, I'll try to be clear about stuff, but if you need clarification, just ask!

Here's what the segmentation fault means:
https://www.geeksforgeeks.org/core-dump-segmentation-fault-c-cpp/

Offhand I'd say your problem is very likely in the Book overloaded constructor, where you have all the this pointers and other pointers.

Do you have a program that uses this class? If so, it would be nice if you would post it here so we don't have to write our own. It just makes it easier for us.

max
No i dont have, it just like a quiz online, all the code is hide from the student, we write the code in the Book class to complie it online a unlimited submit. That is all i have
Ok, it's all good! I can write a short driver for you and test your class.
Thank you for your help max, that means a lot
This is a problem:
1
2
3
4
5
6
	Book (const char *title, const char *authors, int publishingYear)
	{
		*this -> title = *title; // A single character is copied to invalid memory
		*this -> authors = *authors; // A single character is copied to invalid memory
		this -> publishingYear = publishingYear;
	}

And this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	static void printBook (const Book book) // Better use const reference instead of copy: const Book& book
	{
		std::cout << book.title << std::endl;
		
		char *tmp = new char[100]; // Memory is allocated....
		
		tmp = book.authors; // The pointer is replaced with book.authors
		
		while (tmp != NULL)
		{
			std::cout << tmp << std::endl;
		}
		
		delete tmp; // book.authors memory is deleted
		
		std::cout << book.publishingYear << std::endl;
	}
the static void printBook function is the teacher giving one, i can change this. Could you please tell me what should i do to have the correct output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string.h>

    Book(const char *title, const char *authors, int publishingYear)
    {
        if(title)
        {
          this->title = new char[strlen(title) + 1];
          strcpy(this->title, title);
        }
        else
          this->title = nullptr;
        *this->authors=*authors; // same for authors
        this->publishingYear=publishingYear;
    }
1
2
3
4
5
6
7
8
	static void printBook (const Book book)
	{
		std::cout << book.title << std::endl;
		
		std::cout << book.authors << std::endl;
		
		std::cout << book.publishingYear << std::endl;
	}
*authors input is more than one


Can you explain this?

With only one author:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
using namespace std;

class Book {
private:
	char* title {};
	char* authors {};
	int publishingYear {};

public:
	Book() {}

	Book(const char* title_, const char* authors_, int publishingYear_) : publishingYear(publishingYear_)
	{
		if (title_)
			title = strcpy(new char[strlen(title_) + 1], title_);

		if (authors_)
			authors = strcpy(new char[strlen(authors_) + 1], authors_);
	}

	~Book()
	{
		delete[] title;
		delete[] authors;
	}

	Book(const Book&) = delete;		// NEEDS TO BE DEFINED
	Book& operator=(const Book&) = delete;	// NEEDS TO BE DEFINED

	friend class Printer;
};

class Printer
{
public:
	static void printBook(const Book& book)
	{
		cout << book.title << '\n';

		/*
		char* tmp = new char[100];

		// THIS IS AN INFINITE LOOP!
		tmp = book.authors;
		while (tmp != nullptr)
			cout << tmp << endl;

		delete tmp;
		*/
		cout << book.authors << '\n';

		cout << book.publishingYear << '\n';
	}
};

int main()
{
	Book b1("title", "author", 2021);

	Printer::printBook(b1);
}


The Book class also needs a copy constructor and an assignment. These are marked deleted above but they need to be provided if needed.
Last edited on
I dont know how to explain, the question said it is more than one author for 1 book, and the input has 2 names (in vietnamese). Here is the input example given in the test:

Book book1("Giai tich 1", "Nguyen Dinh Huy, Nguyen Thi Xuan Anh", 2000);
Printer::printBook(book1);

Output:
Giai tich 1
Nguyen Dinh Huy
Nguyen Thi Xuan Anh
2000
OK. Now seen what is meant.

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cctype>
using namespace std;

class Book {
private:
	char* title {};
	char* authors {};
	int publishingYear {};

public:
	Book() {}

	Book(const char* title_, const char* authors_, int publishingYear_) : publishingYear(publishingYear_)
	{
		if (title_)
			title = strcpy(new char[strlen(title_) + 1], title_);

		if (authors_)
			authors = strcpy(new char[strlen(authors_) + 1], authors_);
	}

	~Book()
	{
		delete[] title;
		delete[] authors;
	}

	Book(const Book&) = delete;		// NEEDS TO BE DEFINED
	Book& operator=(const Book&) = delete;	// NEEDS TO BE DEFINED

	friend class Printer;
};

class Printer
{
public:
	static void printBook(const Book& book)
	{
		cout << book.title << '\n';

		for (char* str = book.authors; *str; )
			if (*str == ',')
				for (cout << '\n', ++str; *str && isspace(*str); ++str);
			else
				cout << *str++;

		cout << '\n' << book.publishingYear << '\n';
	}
};

int main()
{
	Book book1("Giai tich 1", "Nguyen Dinh Huy, Nguyen Thi Xuan Anh", 2000);

	Printer::printBook(book1);
}



Giai tich 1
Nguyen Dinh Huy
Nguyen Thi Xuan Anh
2000

Last edited on
is there anyway to catch a " , " from input file and change it to "\n " . because authors in the input is several, and each name has to be on one line in the output. Anyways thank you guys for helping me
Yes. See my code above.
Thanks, it works. I pass all the test but still not know what the code means :)).
Thank you guys
What don't you understand?

printBook() iterates through the book string displaying each char until a , is found. It then outputs a newline and skips the , and following spaces. This repeats until the end of the string is found.
Last edited on
Book(const Book &book){ //answer}
I have another issue here too, is this likely to be an operator overload function? Can you guys help me with this one too.
About the previous code you give, I know what you did but it is hard for me to understand what is in the code. This is my first time learning OOP , i ll try my best
In my country we dont have much source about programming, i have to search everything in another language , it confusing me a lot, but at least i got help, that means a lot
Last edited on
Yes. I marked that as =delete in my code above, but the proper code needs to be provided for that to work. It's simply a deep copy of the class members - similar to what was done for the existing constructor. Instead of title_, author_ etc, these come from the function param book.

Ok, is there any e-book for this learning, can you show me. I need help with the code but still want to understand i write it again as my exp, for sure I have assignment about it later
Pages: 12