类函数中的c++字符数组输出
c++ char array output in class functions
我是一个真正的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>
才能使用它们。
- 将值从二维数组输出到文本文件
- 为什么我的数组输出一个不在其中的元素
- 长度为 20 的 Cout'ing 数组输出 23 个字符
- 将矢量数组输出到 tex 文件中,错误
- 来自不同位置的数组输出的执行时间
- 数组输出中缺少字符
- 字符数组输出 - C++
- C 合并的数组输出错误
- 制作垫子类型对象的数组.输出窗口显示同一帧
- C++数组输出地址
- 字符数组输出正确,但实际上没有存储正确的值
- 字符串数组输出
- 为什么在将字符数组输出到控制台时会得到垃圾值
- 字符数组输出额外的字符
- 从字符数组输出到控制台
- 为什么计数从字符数组输出错误的字符
- 动态初始化的 2D 数组输出错误
- C++指针和2d数组输出
- c++中奇怪的char数组输出
- 类函数中的c++字符数组输出