/* name: secondcolumn.cxx */ #include #include #include const int BUFSIZE = 1024; const int ARRAYSIZE = 50; int main(int argc, char** argv) { using namespace std; int ret = 0; if (argc < 2) { // not enough arguments on command line cerr << argv[0] << ": need filename on cmd line" << endl; exit(1); } // used to hold lines of the text file char buffer[BUFSIZE]; // these two pointers are used to identify single words char* startPtr; char* endPtr; // this holds the data char myArray[ARRAYSIZE][ARRAYSIZE][BUFSIZE]; // initialize myArray to empty strings for(int i = 0; i < ARRAYSIZE; i++) { for(int j = 0; j < ARRAYSIZE; j++) { *(myArray[i][j]) = '\0'; } } // open file ifstream myStream(argv[1]); if (!myStream) { cerr << argv[0] << ": cannot open file " << argv[1] << endl; exit(2); } // are we at the end of line? bool isEndLine = false; // is this char a space? bool isSpace = false; // row and column counters int row = 0; int col = 0; int maxRow = 0; int maxCol = 0; // until file ends while(!myStream.eof()) { // read a line in buffer myStream.getline(buffer, (streamsize) BUFSIZE - 1); // set start and end pointers startPtr = buffer; endPtr = startPtr; // while not end of line isEndLine = false; while(!isEndLine) { // look for next space endPtr++; isSpace = false; if (*endPtr == ' ' || *endPtr == '\t') { // found, transform to null char *endPtr = '\0'; isSpace = true; } if (*endPtr == '\0') { // we are at null char, copy this word into myArray isEndLine = true; strncpy(myArray[row][col], startPtr, BUFSIZE - 1); col++; if (col > ARRAYSIZE - 1) { cerr << argv[0] << ": too many columns in text file" << endl; exit(3); } } if (isSpace) { // the char was a space not an end of line, so reset the space *endPtr = ' '; // go to next non-space char while(*endPtr == ' ' || *endPtr == '\t') { endPtr++; } // set start pointer to this char startPtr = endPtr; isEndLine = false; } } if (col > maxCol) { // max column counter maxCol = col; } row++; if (row > ARRAYSIZE - 1) { cerr << argv[0] << ": too many rows in text file" << endl; exit(4); } col = 0; } maxRow = row; double sum = 0; for(int i = 0; i < maxRow; i++) { sum += atof(myArray[i][1]); } cout << "sum = " << sum << endl; #ifdef DEBUG cout << "maxRow = " << maxRow << ", maxCol = " << maxCol << endl; for (int i = 0; i < maxRow; i++) { for(int j = 0; j < maxCol; j++) { cout << myArray[i][j] << " "; } cout << endl; } #endif return ret; }