C++ getline() delimitter

C++ getline() delimitter

本文关键字:delimitter getline C++      更新时间:2023-10-16

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

(15,0,1,#)

(2,11,2,.)

(3,20,0,秒)

我希望能够将整数提取为整数,将字符

提取为字符,但我不知道如何仅提取这些整数。

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

#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';
    }
}

比较从 getline() 的十六进制值获得的值,并运行一些if语句与 ASCII 进行比较。 这会告诉你你是否抓住了一个数字、字母或符号。