【问题标题】:Strange characters when displaying the char array C++显示char数组C++时出现奇怪的字符
【发布时间】:2015-10-28 21:07:16
【问题描述】:

我无法正确显示信息。在文本中显示多余的字符。很可能是零字符的问题,但我无法消除。

第一个文件: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] = '\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;
}

这是我得到的result

【问题讨论】:

  • 学习如何使用调试器并逐行执行代码的充分理由。
  • @πάντα ῥεῖ 信息丰富的答案。
  • 我不认为这是一个问题,但是有什么特别的原因为什么您使用字符串作为名字并使用字符数组作为第二个名字?
  • @ArtemSolovev 当然,这很丰富,但你的问题是火车失事的。
  • @dingalapadum 我是根据书中问题的条件做的。

标签: c++ arrays char output symbols


【解决方案1】:

在第二个构造函数中 m_cFname[0] 没有初始化为 0 使用 strcpy 代替 strcat

你会遇到更长的名字的问题

【讨论】:

  • 我把函数名弄混了。愚蠢的错误。感谢您的帮助
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多