c++ - 使用 C++ 流读取格式化输入

标签 c++ iostream

当使用 stdio.h 时,我可以像这样轻松读取某些类型的格式化输入:

FILE* fin = fopen(...);
fscanf(fin, "x = %d, y = %d", &x, &y);

这样做的好处是,我真的不必担心字符“x”和后面的“=”之间有多少空格,以及其他小细节。

在我看来,在 C++ 中,

ifstream fin(...);
string s;
fin >> s;

可能导致 s"x""x=",甚至 "x=12"取决于输入的间距。

有没有一种方便的方法可以使用 iostream/fstream 获得类似于 scanf/fscanf 的行为?

最佳答案

如果有先决条件,这实际上出奇地容易。我有这三个功能,我把它们贴在某个地方的标题中。这些允许您流式传输字 rune 字和字符串文字。我一直不太明白为什么这些不是标准的。

#include <iostream>

//These are handy bits that go in a header somewhere
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&sliteral)[N]) {
        e buffer[N-1] = {}; //get buffer
        in >> buffer[0]; //skips whitespace
        if (N>2)
                in.read(buffer+1, N-2); //read the rest
        if (strncmp(buffer, sliteral, N-1)) //if it failed
                in.setstate(std::ios::failbit); //set the state
        return in;
}
template<class e, class t>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& cliteral) {
        e buffer(0);  //get buffer
        in >> buffer; //read data
        if (buffer != cliteral) //if it failed
                in.setstate(std::ios::failbit); //set the state
        return in;
}
//redirect mutable char arrays to their normal function
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) {
        return std::operator>>(in, carray);
}

有了这些,剩下的就简单了:

in>>'x'>>'='>>data.first>>','>>'y'>>'='>>data.second;

Proof here

对于更复杂的情况,您可能想使用 std::regexboost::regex,或者可能是真正的词法分析器/解析器。

关于c++ - 使用 C++ 流读取格式化输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17244181/

相关文章:

c++ - 关于在 Xcode 中使用 C++ 构建 MacOSX GUI 应用程序的指南、教程或书籍?

c++ - SWIG 将流从 python 传递到 C++

c++ - 错误:不匹配 std::operator<<<std::char_traits<char>>(*&std::cout),((const char*) 中的 operator<<

c++ - 在 Qt 中包含 OpenGL 库

c++ - 错误 C2664 : 'callToPrint' : cannot convert parameter 1 from 'std::wstring' to 'LPTSTR'

c++ - 如何清除cin读取的内容

c++ - 代码块上的 Iostream 问题?

c++ - 读取多行文本直到空行

c++ - Qt4 中的析构函数

c++ - 如何将此 C 代码转换为 C++?