类函数中的c++字符数组输出

c++ char array output in class functions

本文关键字:数组 输出 字符 c++ 类函数      更新时间:2023-10-16

我是一个真正的c++初学者,在c++异常中我的char数组输出有问题。我被要求将某个UML类转换为c++,并用main中给出的参数生成一个工作输出。这是代码:

#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;

这是我的输出:

Book Nr: 123456
Author: b<Vv-[[vóYA
Year: 2014
Lent [yes/no]: no
Press any key to continue...

正如你所看到的,除了"作者"之外,所有的输出都有效。在那里我得到了垃圾。注意,我必须使用char作为类型。因为它是在UML类中给出的,所以我不得不转换为c++。

我真的到处找。但没有找到正确的解决方案。我觉得这将是一个非常简单的。。。

提前感谢您的帮助!

这不起作用的原因是,您正在将指针author分配给另一个指示器a,然后超出范围。。。所以author只能指向一些垃圾。如果你想坚持使用字符数组,你必须复制a指向的所有数据:

strcpy(author, a);    

但由于它是C++,您应该只使用字符串,这更容易处理:

class Book {
    ...
    std::string author;
    ....
};
Book::Book(long int n, const std::string& a, int j, bool x)
: author(a), ...
{ }

您正在打印未初始化的数据。

使作者成为字符串

#include <string>
class Book
{   protected: 
        long int number; 
        std::string author;
        int year;
        bool lent;

并使构造函数的参数也成为字符串

Book::Book(long int n, const std::string& a, int j, bool x)

字符数组不如std::字符串灵活。它们只是数据块。如果要使用字符串,请改用std::string

此外,在C++构造函数中使用初始值设定项列表,而不是java风格的

Book::Book(long int n, const std::string &a, int j, bool x)
    : number(n),
    author(a),
    year(j),
    lent(x)
{ }

您的代码中有两个错误:

Book::Book(long int n, const char a[25], int j, bool x)
{
    number=n;
    strncpy(author, a, 25);  // author = a;  doesn't work! shouldn't compile either...
    year=j;
    lent=x;
}

第一:变量author是指向以零结尾的字符串的指针。您可以使用strcpy()来复制此字符串。因此,您需要#include <memory.h。但您需要确保字符串-是-真的以零结尾,并且适合您的目标变量!否则,您将覆盖目标变量旁边的其他内存区域,这也称为缓冲区溢出!更好地使用strncpy(target,source,maxlength);这避免了这个问题。

第二:您的参数a应该是"const",因为您希望能够像Book b1(123456, "test", 2014, false);中那样用字符串常量来调用它,其中"test"是常量!

正如其他人已经建议的那样,您应该使用std::string而不是a[25]。C字符串是"C"而不是"C++",您应该尽量避免它们。C字符串会在代码中引入很多错误,并导致缓冲区溢出(=安全问题)。而且它们处理起来更复杂。您需要#include <string>才能使用它们。