gpt4 book ai didi

C++ getline() 分隔符

转载 作者:行者123 更新时间:2023-11-28 03:08:43 25 4
gpt4 key购买 nike

嘿,我正在尝试使用 getline 读取以下行

(15,0,1,#)

(2,11,2,.)

(3,20,0,S)

我希望能够将整数提取为 int,将字符提取为 char,但我不知道如何只提取它们。

最佳答案

您似乎可以读出分隔符,即 '(', ')'',' 然后就可以了使用格式化输入。为操纵器使用一个简单的模板应该可以很好地解决问题:

#include <iostream>
#include <sstream>

template <char C>
std::istream& read_char(std::istream& in)
{
if ((in >> std::ws).peek() == C) {
in.ignore();
}
else {
in.setstate(std::ios_base::failbit);
}
return in;
}

auto const open_paren = &read_char<'('>;
auto const close_paren = &read_char<')'>;
auto const comma = &read_char<','>;

int main()
{
int x, y, z;
char c;
std::istringstream in("(1, 2, 3, x)\n(4, 5, 6, .)");
if (in >> open_paren >> x
>> comma >> y
>> comma >> z
>> comma >> c
>> close_paren) {
std::cout << "x=" << x << " y=" << y << " z=" << z << " c=" << c << '\n';
}
}

关于C++ getline() 分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19035837/

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