0

Hey I am trying to read in the following lines using a getline

(15,0,1,#)

(2,11,2,.)

(3,20,0,S)

I want to be able to just extract the integers as ints and the characters as char, but I have no idea how to only extract those.

P0W
  • 46,614
  • 9
  • 72
  • 119
  • Read `char int char int char int char char`, check if it succeeded, check the contents. – jrok Sep 26 '13 at 18:30

2 Answers2

3

It seems you could read off the separators, i.e., '(', ')', and ',' and then just use the formatted input. Using a simple template for a manipulator should do the trick nicely:

#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';
    }
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
-1

Compare the value you get from getline()'s hexadecimal value, and run some if statements to compare to ASCII. That will tell you if you grabbed a number, letter, or symbol.

armani
  • 93
  • 1
  • 10
  • 23