c++ istream中的行号
Line number in a C++ istream?
假设我正在从std::istream
读取令牌。知道从流中读取的换行数的好方法是什么?这是为了在解析器中报告错误。我不想用std::getline
来读取输入
这是一个测试用例。我正在寻找功能类似于GetLineNumber
的东西,在这种情况下,它将返回最后读令牌的行号。
std::stringstream ss;
ss << "1 n 2 n 3 n";
int x;
while (ss >> x) {
std::cout << "Line " << GetLineNumber(ss) << ": " << x << std::endl;
}
这个例子的输出应该是:
Line 1: 1
Line 2: 2
Line 3: 3
您可以使用过滤流buf,并在那里保持计数:
class LineNumberStreambuf : public std::streambuf
{
std::streambuf* mySource;
std::istream* myOwner;
bool myIsAtStartOfLine;
int myLineNumber;
char myBuffer;
protected:
int underflow()
{
int ch = mySource->sbumpc();
if ( ch != EOF ) {
myBuffer = ch;
setg( &myBuffer, &myBuffer, &myBuffer + 1 );
if ( myIsAtStartOfLine ) {
++ myLineNumber;
}
myIsAtStartOfLine = myBuffer == 'n';
}
return ch;
}
public:
LineNumberStreambuf( std::streambuf* source )
: mySource( source )
, myOwner( nullptr )
, myIsAtStartOfLine( true )
, myLineNumber( 0 )
{
}
LineNumberStreambuf( std::istream& owner )
: mySource( owner.rdbuf() )
, myOwner( &owner )
, myIsAtStartOfLine( true )
, myLineNumber( 0 )
{
myOwner->rdbuf( this );
}
~LineNumberStreambuf()
{
if ( myOwner != nullptr ) {
myOwner.rdbuf( mySource );
}
}
int lineNumber() const
{
return myLineNumber;
}
};
把这个插入到你的输入中:
LineNumberStreambuf ln( std::cin );
// ...
std::cerr << "Error (" << ln.lineNumber << "): ..." << std::endl;
注意,行号只反映输入的值
相关文章:
- 为什么istream不支持右值提取
- 将无符号char*转换为std::istream*C++
- 需要从 istream 和 ostream 派生 iostream
- 使用std::istream::peek()总是安全的吗
- 使用 istream 参数读取的 istream 函数
- istream std::cin如何修改自定义istream缓冲区
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 在清除 istream 之前,我不应该需要取消获取它吗?
- C++,如何根据运行时条件构造引用不同 istream 对象的对象?
- 如何将QByteArray转换为std::istream或std::ifstream?
- 逗号在重载 ostream 和 istream 在结构中分开
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- 从函数返回 istream 的正确方法
- 阅读从 istream 到矢量的不同类型列表
- 关于 istream 中的错误处理的问题
- C++ 模板类无法修复 ostream 和 istream 函数
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- iStream 运算符跳过空格字符
- 如何在 c++ 中将 IStream 转换为 Base64 字符串
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?