c++ - Extraction operator causing my program to exit? -
i'm usual lurker first post! understand guys detail best. appreciate whatever input has.
i working on overloading extraction operator object dynamic array of digits. console input have leading white space, int, after. need ignore white space, extract int, , leave rest alone. easy right?
here example of code found online:
istream & operator >> (istream &m, myint & p) { int x = 0; p.currentlength = 0; while ((m.peek() == '\n') || (m.peek() == '\0') || (m.peek() == '\t') || (m.peek() == ' ')) { m.get(); } while ((m.peek() >= '0') && (m.peek() <= '9')) { if (p.currentlength >= p.maxsize) { p.grow(); } m >> p.thenumber[x]; x++; p.currentlength++; } m.get(); // reverse order (i.e. - 123 321) char * temp = new char[p.maxsize]; (int y = 0; y < p.currentlength; y++) { temp[y] = p.thenumber[p.currentlength - 1 - y]; } delete [] p.thenumber; p.thenumber = temp; return m; }
now, understand method may work, me, seems extremmeelly inefficient method. trillion digit number, grow() reallocate array trillion times! perhaps not bad think is?
my current method has been using seekg() , peek() , get(). so:
istream& operator >> (istream& is, myint& z) { int = 0, j = 0; // check if next char white while (is.peek() == 38) { j++; is.seekg(j); // skip if white } while (isdigit(is.peek())) { i++; is.seekg(j + i); if (!is.peek()) { is.clear(); break; } } is.seekg(j); z.length = i; z.digits = new int[i + 1]; (i = 0; < z.length; i++) { z.digits[i] = c2i(is.get()); } return is; }
also, here main:
int main() { myint b; cout << "\n\nchange b num? ---> "; cin >> b; cout << "b now: " << b; char c; cout << "\n\n\n\n\nenter char exit : "; cin >> c; return 0; }
for life of me can not find causing program exit. last output seems say, 'b now: -1'
i believe means << b failed. have b initialized 0 currently, , rest of code has presented no other issues. it's private member data include pointer , length (num of digits). c2i() function converts '0' through '9' 0 through 9.
a big issue me new parsing, don't have eloquent ways test this, or other ideas.
again appreciate guys do. have learned great deal browsing here!
Comments
Post a Comment