构造函数未按预期工作

时间:2017-02-25 07:34:18

标签: c++

我试图让这个构造函数来做这些事情:

此构造函数尝试打开传递其名称的文件 在文件名中。如果文件成功打开,则调用函数 getFileSize确定应分配多少字节 对于消息。为消息分配空间并读取消息 从文件内容到它。最后关闭文件。 成员变量长度应设置为文件大小。 如果找不到文件,则应将长度设置为零。

我目前遇到了麻烦,当我尝试运行程序时出现错误,因为它甚至没有读取我的文件并且无法理解问题。任何帮助将不胜感激。

构造

Message::Message(std::string filename) {
    fstream fin(filename);
    if (fin.fail())
    {
        cout << "failed";
    }
    else {
        length = getFileSize(fin);
        message = new char[length];
        fin.getline(message, length); {
            fin >> message;
        }
    }
    fin.close();
}

.h文件:

#ifndef MESSAGE_H_
#define MESSAGE_H_

#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <iostream>

class Message
{
private:
    char *message;   // holds the message
    int length;  // holds the the message length
    static const short ALPHABET_SIZE = 26;
    char code[ALPHABET_SIZE]; // holds the cypher alphabet
                              // iztohndbeqrkglmacsvwfuypjx
                              // ex: an 'a' in the original message should be converted to 'i', 'b' should be converted to 'z' and so forth

    // returns the input file size in bytes
    std::streamsize getFileSize(std::fstream &file) const
    {
        std::streamsize fsize = 0;
        file.seekg(0, std::ios::end);
        fsize = file.tellg();
        file.seekg(0, std::ios::beg); // moves file pointer back to the beginning
        return fsize;
    }
public:
    Message(std::string filename);
    // The destructor frees the space allocated to message
    virtual ~Message();
    // Decodes the message
    void decode();
    // Capitalizes first letter in each sentence
    void fixCapitalization();
    // Prints the content of message on the screen
    void dump() const;
    // Returns true if the message is empty
    bool isEmpty() const;
};

以下是我的文件:

OBJECT.CPP:

#include "Message.h"

using namespace std;

Message::Message(std::string filename) {
    fstream fin(filename);
    if (fin.fail())
    {
        cout << "failed";
    }
    else {
        length = getFileSize(fin);
        message = new char[length];
        fin.getline(message, length); {
            fin >> message;
        }
    }
    fin.close();
}

Message::~Message()
{
    //dtor
}
void Message::decode() {
    int offset;
    strcpy(code, "iztohndbeqrkglmacsvwfuypjx");
    for (int i = 0; i < strlen(message); i++) {
        if (message[i] == ' ') continue;
        if (message[i] == ',') continue;
        if (message[i] == '.') continue;
        offset = int(message[i] - 'a');
        message[i] = code[offset];
    }
}

void Message::fixCapitalization() {
    for (int i = 0; i < strlen(message); i++) {
        if (message[0] != ' ' || message[0] != ',') {
            message[0] = toupper(message[0]);
        }
        if (message[i] == '.' || message[i] == '?' || message[i] == ',') {
            message[i + 2] = toupper(message[i + 2]);
        }
    }
}

void Message::dump() const {
    for (int i = 0; i < strlen(message); i++) {
        cout << message[i];
    }
}

bool Message::isEmpty() const {
    if (length == 0) {
        return true;
    }
    else {
        return false;
    }
}

.H文件:

/*
* Message.h
*
*  Created on: Dec 11, 2016
*      Author: hellenpacheco
*/

#ifndef MESSAGE_H_
#define MESSAGE_H_

#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <iostream>

class Message
{
private:
    char *message;   // holds the message
    int length;  // holds the the message length
    static const short ALPHABET_SIZE = 26;
    char code[ALPHABET_SIZE]; // holds the cypher alphabet
                              // iztohndbeqrkglmacsvwfuypjx
                              // ex: an 'a' in the original message should be converted to 'i', 'b' should be converted to 'z' and so forth

                              // returns the input file size in bytes
    std::streamsize getFileSize(std::fstream &file) const
    {
        std::streamsize fsize = 0;
        file.seekg(0, std::ios::end);
        fsize = file.tellg();
        file.seekg(0, std::ios::beg); // moves file pointer back to the beginning
        return fsize;
    }
public:
    /*
    * This constructor tries to open the file whose name is passed
    * to it in filename. If file opens successfully, calls function
    * getFileSize to determine how many bytes should be allocated
    * for the message. Allocates space for message and reads the
    * content from the file into it. Closes the file at the end.
    * Member variable length should be set to the file size.
    * If file cannot be found, length should be set to zero.
    */
    Message(std::string filename);

    // The destructor frees the space allocated to message
    virtual ~Message();

    // Decodes the message
    void decode();

    // Capitalizes first letter in each sentence
    void fixCapitalization();

    // Prints the content of message on the screen
    void dump() const;

    // Returns true if the message is empty
    bool isEmpty() const;
};



#endif /* MESSAGE_H_ */

main.cpp中:

#include <iostream>
#include <stdlib.h>
#include <fstream>
#include "Message.h"

using namespace std;

int main()
{
    // create a message object with the content of Encrypted.txt
    Message m("Encrypted.txt");

    if (m.isEmpty())
    {
        cout << "Could not read message";
        return EXIT_FAILURE;
    }
    cout << "Original message: " << std::endl;
    m.dump();
    cout << std::endl << std::endl;
    m.decode();
    m.fixCapitalization();
    cout << "Decoded message: " << std::endl;
    m.dump();
    cout << std::endl << std::endl;

    return EXIT_SUCCESS;
}

以下文件是我尝试打开并解码的.txt文件,并且全部在一行:

ifqkwxcadf ar cei fpoi masif cd cei xkdqirr du pxxnwafm pf pnmdkaceo cd p oirrpmi, teaqe rqkpohnir cei gpcp af ac-oplafm ac sikw gauuaqvnc pfg caoi qdfrvoafm, au fdc xkpqcaqpnnw aoxdrrahni, cd gigvqi cei dkamafpn masif dfnw cei ifqdgig gpcp. afxvcr cd cei pnmdkaceo cwxaqpnnw afsdnsi pggacadfpn riqkic gpcp qpnnig liwr, teaqe xkisifcr cei oirrpmi ukdo hiafm giqdgig-isif au cei pnmdkaceo ar xvhnaqnw lfdtf.

1 个答案:

答案 0 :(得分:0)

的问题
    message = new char[length];
    fin.getline (message, length); {
        fin >> message;
    }
    如果遇到换行符,
  1. getline将停止。
  2. fin >> message;行将覆盖getline中的内容。
  3. {}根本没有意义。它们本身并不是问题,但它们让我觉得你不清楚你想要做什么。
  4. 我会将这些行改为

        message = new char[length + 1];  // Add an extra character if
                                         // message is supposed to be null
                                         // terminated.
        fine.read(message, length);
        message[length] = '\0';