/* numbers.cpp - Matt Mahoney, mmahoney@cs.fit.edu This program reads text from standard input and outputs a list of integers extracted from the text in ascending order. A number is any sequence of one or more digits (0-9) possibly with a leading minus sign, but no other characters. For example, if the input is "-3.75-$1.05", the output is -3 1 5 75 */ #include #include #include #include // sort() #include // isdigit() #include // atoi() using namespace std; int main() { vector v; // List of numbers extracted so far, e.g. -3, 75. string s; // Characters making up a number so far, e.g. "-" or "-3" char c; // Current character, e.g. '-' or '3' /* Extract numbers and put into v. A number has 0 or 1 minus signs followed by 1 or more digits. The following 3 x 3 state table describes how the input is parsed. The 3 possible states of s are "", "-", and "number", representing all other possible values. The 3 possible inputs are '-', a digit (0-9), or another character. State Input Next state Action ----- ----- ---------- ------ "" '-' "-" "" digit "digit" "" other "" "-" '-' "-" "-" digit "-digit" "-" other "" number '-' "-" Store number in v number digit "number+digit" number other "" Store number in v */ while (cin.get(c)) { if (s == "") { if (isdigit(c) || c=='-') s += c; } else if (s == "-") { if (isdigit(c)) s += c; else if (c != '-') s = ""; } else { if (isdigit(c)) s += c; else { v.push_back(atoi(s.c_str())); s = ""; if (c == '-') s += c; } } } // Handle any leftover characters at end of file (handle as input 'other') if (s != "" && s != "-") v.push_back(atoi(s.c_str())); // Sort and print sort(v.begin(), v.end()); for (int i=0; i