【发布时间】:2017-10-26 04:01:27
【问题描述】:
我需要将文件内容读入某些对象,不幸的是我不能随意使用 std::string ,因此必须使用 char 指针。 但是,当我这样做时,我会直接从内存中得到奇怪的迹象,但 solution 却不起作用。 所以我通过直接从istream而不是std库使用getline来重建,但同样的情况发生了。 如何在不使用 std::string 的情况下正确读取文件。
PortsContainer game::ParsePort(std::istream& stream)
{
PortsContainer ports;
bool passFirstRow = false;
char* portLine = new char[1000000];
int i = 0;
while (!stream.eof())
{
if (!stream)
throw std::system_error(Error::STREAM_ERROR);
if (portLine[0] == '\0' || portLine == nullptr || portLine[0] == '#')
continue;
std::stringstream ss(portLine);
if (!passFirstRow) {
char* name = new char[100];
while (!ss.eof()) {
ss.getline(name, sizeof name, ';');
Port* port = new Port();
//port->name = const_cast<char*>(name);
port->name = const_cast<char*>(name);
ports.addItem(port);
}
passFirstRow = true;
} else {
i++;
}
if (!stream)
throw std::system_error(Error::STREAM_ERROR);
}
return ports;
}
PortsContainer game::ParsePort(std::istream& stream, std::error_code& errorBuffer)
{
try
{
return ParsePort(stream);
}
catch (std::system_error exception)
{
errorBuffer = exception.code();
}
}
PortsContainer game::GetAvailablePorts()
{
PortsContainer ports;
std::ifstream stream("./ports.csv");
std::error_code errorBuffer;
ports = ParsePort(stream, errorBuffer);
if (errorBuffer)
return PortsContainer();
return ports;
}
【问题讨论】:
-
首先我建议你阅读Why is iostream::eof inside a loop condition considered wrong?。那么你应该记住,C++ 中的
char字符串实际上称为null-terminate 字节字符串。空终止符(不要与空指针混淆)很重要。还要记住,您分配的内存将不会被初始化,即使读取它也会导致未定义的行为。最后,您可能到处都有一些内存泄漏。 -
sizeof name你期望什么价值? -
我不能随意使用 std::string YAIT(又一个不称职的老师)
-
不允许您使用
std::string但您可以使用基于std:: string的std::stringstream是没有意义的 -
你从来没有读过
stream的文章,这怎么能正常阅读?