显示字符数组C++时出现奇怪字符
Strange characters when displaying the char array C++
我无法正确显示信息。在文本中显示了额外的字符。很可能是零字符的问题,但我没能消除。
第一个文件:person.h这里我描述一个简单的类。
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#include <string>
using std::string;
class Person
{
private:
static const int m_iLIMIT = 25;
string m_sLname; // lastname
char m_cFname[m_iLIMIT]; // firstname
public:
Person () { m_sLname = ""; m_cFname[0] = ' '; } // #1
Person(const string & sLn, const char * pcFn = "Adam"); // #2
// show lastname и firstname
void Show() const; // format: firstname lastname
void FormalShow() const; // format: lastname, firstname
};
#endif // PERSON_H_INCLUDED
第二个文件:p_functions.cpp这里我定义类方法
#include "person.h"
#include <iostream>
#include <string>
#include <cstring>
using std::string;
using std::cout;
using std::cin;
using std::endl;
// #2
Person::Person(const string & sLn, const char * cFn)
{
m_sLname = sLn;
strcat(m_cFname, cFn);
}
void Person::Show() const
{
cout << "First format: " << m_cFname << ", " << m_sLname << endl;
}
void Person::FormalShow() const
{
cout << "Second format: " << m_sLname << ", " << m_cFname << endl;
}
第三个文件:main.cpp这里是测试方法
#include <iostream>
#include "person.h"
using namespace std;
int main()
{
Person one;
Person two("Smith");
Person three("immanuel", "Kant");
one.Show();
one.FormalShow();
two.Show();
two.FormalShow();
three.Show();
three.FormalShow();
return 0;
}
这是我得到的结果
在第二个构造函数中m_cFname[0]没有用0初始化使用strcpy而不是strcat
并且您将遇到名字较长的问题
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?