gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:38:15 26 4
gpt4 key购买 nike

当使用 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/

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