gpt4 book ai didi

c++ - 检查流是否以换行符结尾

转载 作者:太空狗 更新时间:2023-10-29 21:36:37 29 4
gpt4 key购买 nike

我想检查流(实际上是 ifstream)是否以换行符结尾。我想出了这个:

bool StreamEndsWithNewline(std::basic_istream<char> & the_stream)
{
if (the_stream.peek() == EOF) {
the_stream.clear(); //clear flags set by peek()
return false;
}
std::string line = "blah";
while (std::getline(the_stream, line)) {
// ...
}
return line.empty();
}

想法是,如果流的最后一行有一个 \n 结束字符,while 循环将进行一次额外的迭代(因为尚未达到 eof),其中空字符串将被分配给行参数。

必须单独处理“空”流的特殊情况。

它似乎适用于 Windows (vs2010)。我一般可以这样做吗?

最佳答案

您的代码有效。

但是,您可以尝试查找流并仅测试最后一个字符或丢弃读取的字符:

#include <cassert>
#include <iostream>
#include <limits>
#include <sstream>

bool StreamEndsWithNewline(std::basic_istream<char>& stream) {
const auto Unlimited = std::numeric_limits<std::streamsize>::max();
bool result = false;
if(stream) {
if(std::basic_ios<char>::traits_type::eof() != stream.peek()) {
if(stream.seekg(-1, std::ios::end)) {
char c;
result = (stream.get(c) && c == '\n');
stream.ignore(Unlimited);
}
else {
stream.clear();
while(stream && stream.ignore(Unlimited, '\n')) {}
result = (stream.gcount() == 0);
}
}
stream.clear();
}
return result;
}

int main() {
std::cout << "empty\n";
std::istringstream empty;
assert(StreamEndsWithNewline(empty) == false);

std::cout << "empty_line\n";
std::istringstream empty_line("\n");
assert(StreamEndsWithNewline(empty_line) == true);

std::cout << "line\n";
std::istringstream line("Line\n");
assert(StreamEndsWithNewline(line) == true);

std::cout << "unterminated_line\n";
std::istringstream unterminated_line("Line");
assert(StreamEndsWithNewline(unterminated_line) == false);

std::cout << "Please enter ctrl-D: (ctrl-Z on Windows)";
std::cout.flush();
assert(StreamEndsWithNewline(std::cin) == false);
std::cout << '\n';

std::cout << "Please enter Return and ctrl-D (ctrl-Z on Windows): ";
std::cout.flush();
assert(StreamEndsWithNewline(std::cin) == true);
std::cout << '\n';

return 0;
}

关于c++ - 检查流是否以换行符结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704088/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com