【发布时间】:2020-01-10 06:11:38
【问题描述】:
所以我为 MyString 类重载了一个运算符“>>”。它应该从文本文件中读取信息到自定义字符串,但是当我尝试按字符填充字符串时出现异常。 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;
};
【问题讨论】:
-
delete之后哪里有空间放Character?
标签: c++ ios class overloading operator-keyword