【问题标题】:C++ getline() delimitterC++ getline() 分隔符
【发布时间】:2013-09-26 18:25:54
【问题描述】:

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

(15,0,1,#)

(2,11,2,.)

(3,20,0,S)

我希望能够将整数提取为 int,将字符提取为 char,但我不知道如何仅提取这些。

【问题讨论】:

  • 读取char int char int char int char char,查看是否成功,查看内容。

标签: c++ getline cin


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-10
      • 2013-10-21
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2016-10-27
      相关资源
      最近更新 更多