/* COMP2401/2001 Assignment #1 - Problem #5 http://people.scs.carleton.ca/~mjhinek/W13/COMP2401/assignments/ass1.html mjh 2013 */ #include // helper functions // isLetter: char -> int // Purpose: return 1 if input is a letter [a..zA..Z] // return 0 otherwise // Examples: isLetter('a') -> 1 // isLetter('-') -> 0 int isLetter(char in){ return ( (in >= 65 && in <= 90) || (in >= 97 && in <= 122)); } // isDigit : char -> int // Purpose : return 1 if input is a decimal digit // return 0 otherwhise // Examples: isDigit('2') -> 1 // isDigit('a') -> 0 int isDigit(char in){ return (in >= 48) && (in <=57); } // chatToInt : char -> int // Purpose : convert charater of a digit to the digits value // Precondition: input character is a digit. // Thus, input satisfies isDigit(input) == 1 // Example : charToInt('3') -> 3 int charToInt(char in){ // shift input value by 48 (ascii value of zero) return in - 48; } // convert : char -> char // Purpose : convert case of input character // Precondition: input character is a letter // Thus, input satisfies isLetter(input) == 1 // Examples : convert('s') -> 'S' // convert('Q') -> 'q' char convert(char in){ if( in>=65 && in<=90) // convert uppercase to lowercase return in+('a'-'A'); else // convert lowercase to uppercase return in-('a'-'A'); } int main(){ // We will consider two consecutive chars at a time. // Given the second input, we process the first. // // the sequence '\\' 'n' is special and we treat it // slightly differently (as we skip ahead to the next // next char once we print '\n') char previous = '\0'; // first char char current = '\0'; // second char int lastInt = 2; // previous digit value int count = 1; // count for repeating letters // always default to 1 // read in first char scanf("%c", &previous); while(1){ // loop until we find QQQ // read second char scanf("%c", ¤t); if (isDigit(previous) ){ // deal with digits first // multiply digit by previous digit int currentInt = charToInt(previous); printf("%d", lastInt * currentInt); lastInt = currentInt; }else if(previous == 32){ // ascii 32 == space // convert space to underscore printf("_"); }else if(isLetter(previous)){ // process letters if(previous == current){ // repeated letters count += 1; // check if we should exit the program if (count == 3 && previous == 'Q'){ printf("\n"); return 0; } }else{ // print out first/previous character printf("%c",convert(previous)); if (count > 1) printf("%d", count); count = 1; // reset counter } }else if(previous == '\\' && current == 'n'){ // process \n printf("\n"); scanf("%c",¤t); }else{ // everything else is simply echoed to output printf("%c", previous); } // let first be the second and repeat the loop... previous = current; } }