1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
/*
* Read a text file whose name is given on the command line, and for each word:
* if it is an integer, insert it into an array in sorted order
* if it is not an integer, insert it into an array of words.
*
* Notes: converted to use C++ strings, because C strings are messier.
* Need to grow arrays, need to insert in sorted order.
* Growing arrays might be done the way we grew a C string:
*
* bigger = new <type> [size+1]
* for(i=0; i<size; i++) {
* bigger[i] = oldarray[i];
* }
* size++;
* delete oldarray;
* oldarray = bigger;
*
* Note that the new array has an "empty" element at its end. Can assign
* it directly to add a value at the end. To insert: copy elements from
* the back up one index value, until you get to where you wanted to open
* up a hole.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctype.h>
using namespace std;
int mywhite(char c)
{
switch (c) {
case ' ': case '\t': case '\n': return 1;
}
return 0;
}
int is_integer(string s)
{
if (s.size() == 0) return 0;
for(int i=0; i<s.size(); i++) {
if (isdigit(s[i]) == 0) return 0;
}
return 1;
}
int main(int argc, char *argv[])
{
int *ai = NULL; /* "array" of integers */
string *as = NULL; /* "array" of strings */
string theString;
char c;
int i;
int size = 0;
ifstream f;
if (argc < 2) {
cout << "usage: arraygrow filename" << endl;
exit(1);
}
f.open(argv[1]);
if (f.fail()) {
cout << "can't open " << argv[1] << endl;
exit(1);
}
cout << "opened " << argv[1] << ", seemingly OK" << endl;
theString = ""; // starts as empty string
if (f.eof()) {
cout << "die die die" << endl;
exit(1);
}
// not >> because >> skips over whitespace
c = f.get();
while (! f.eof()) {
// read one word worth of the input file
// skip over white space until we have at least one non-whitespace char
while (mywhite(c)) {
if (f.eof()) break;
// not >> because >> skips over whitespace
c = f.get();
}
if (f.eof()) {
// we are end of file, but might have seen a non-white character
// as our final one, might need to add logic here.
break;
}
// to get here, we must have found a non-whitespace character,
// so we have a word coming.
// if it is whitespace we are done.
for ( ; !mywhite(c); ) {
// add the character to the end of our current "word"
theString = theString + c;
size++;
// read another character, IF YOU CAN
if (f.eof()) break;
// not >> because >> skips over whitespace
c = f.get();
}
if (is_integer(theString)) {
cout << theString << " is an integer" << endl;
}
else {
cout << theString << " is something else" << endl;
}
// start the next word
size = 0;
theString = "";
}
}
|