在重载运算符>>部分中接收异常

时间:2019-09-07 21:49:56

标签: c++ ios class overloading operator-keyword

因此,我为班级MyString重载了运算符“ >>”。本来应该将信息从文本文件读取到定制字符串中,但是当我尝试用char填充字符串char时出现了异常。 Text.txt仅包含“ xyz”

Main.cpp:

#include "MyString.h"
#include <fstream>
#include <iostream>
//TO-DO 1 CharArr for all
int main() {

    MyString NewString;
    ifstream In("Text.txt");
    In >> NewString;

    cout << NewString << endl;
    system("pause");
    return 0;
}

构造函数:

MyString::MyString() {
    StringLength = 0;
    Pointer = nullptr;
}

MyString::MyString(const char* String) {
    for (int i = 0; String[i]; i++)
    StringLength++;
    Pointer = new char[StringLength + 1];
    char *Source = (char *)String;
    char *Destination = (char *)Pointer;
    for (int i = 0; i < StringLength + 1; i++)
    Destination[i] = Source[i];
}

操作员:

istream &operator>>(istream &In, MyString &String) {
    int FileStringLength = 0;
    char Character;
    if (String.Pointer != nullptr)
        delete[] String.Pointer;
    while (In.get(Character) && Character != '\n')
        FileStringLength++;
    if (FileStringLength < 1000 && FileStringLength != 0) {
        String.StringLength = FileStringLength;
        In.clear(), In.seekg(0, ios::beg);
        for (int i = 0; In.get(Character) && Character != '\n'; i++)
                String.Pointer[i] = Character; // I get an exception here
    }
    else if (!FileStringLength) {
        cout << "File is empty." << endl;
    }
    else {
        cout << "File contains too many characters." << endl;
    }

    return In;
};

1 个答案:

答案 0 :(得分:0)

  <style name="OutlinedRoundedBox" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.TextInputLayout.Rounded</item>
  </style>

  <style name="ShapeAppearanceOverlay.MyApp.TextInputLayout.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">8dp</item>
  </style>

释放了

的存储空间
if (String.Pointer != nullptr)
    delete[] String.Pointer;

将要使用。

解决方案:

不要String.Pointer[i] = Character; // I get an exception here 存储。而是将其覆盖直到存储空间写满,然后分配一个更大的新缓冲区进行存储,将旧缓冲区复制到新缓冲区中,然后释放旧缓冲区。