Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For this part of the assignment, you will need to write a program that accepts 1

ID: 3873381 • Letter: F

Question

For this part of the assignment, you will need to write a program that accepts 1 single string as program argument and compresses it by counting each repeating letter that occurs in the string and the number of times it occurs in the string as such:

Example 1:

$./sixth aaaabbbccdaaaa

a4b3c2d1a4

Example 2:

$./sixth abcccccccggeeccccd

a1b1c7g2e2c4d1

Also, if the compressed string would be longer than the original string, you must output the original string instead.

Example 3:

$./sixth abc

abc

Characters need not be unique, and your program should only count consecutive repeating letters in a string. Matching letters delimited by another differing letter must appear as such in the string as well (see example 1). Your input can be (a-z, A-Z, any symbols). All invalid input such as numbers or invalid program arguments must be met with an ”error” output and the program should exit with code 0 (i.e., exit(0)).

Example 4:

$./sixth 111111bb aaaaa

error

Explanation / Answer

#include<iostream>
#include<string>
#include<sstream>
#include<stdlib.h>
#include<string.h>

using namespace std;

int main(int argc, char **argv){

   char *str;
   int i = 0;
   int count;
   int k;
  
   if (argc != 2){
      cout << "Error: Invalid number of arguments! ";
      exit(0);
   }

   str = argv[1];
   string str1 = "";

   i = 0;
   while (i<strlen(str)){
        if ( str[i] >= '0' && str[i] <= '9'){
           cout << "Error: Invalid input! ";
           exit(0);
        }
        else {
            str1 = str1 + str[i];
            k = i;
            count = 0;
            while (str[k] == str[i]){
                k++;
                count++;
            }
           if (count > 0){
              stringstream ss;
              ss << count;
              str1 = str1 + ss.str();
              i = i + count;
           }
           else {
               i = i +1;
           }
               
        }
   }
   if (str1.size() > strlen(str))
      cout << str << endl;
   else
      cout << str1 << endl;
   exit(0);   
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote