lundi 11 janvier 2021

Cancel the loop when the if condition is not true

I'm trying to write a program that does Run-Length-Encoding. I wrote the program but I want to cancel the entire loop when there is a non-alphabet character in input. I mean, it should give an output like "The input is not valid!".

I tried several if conditions but every time it encodes the alphabet characters till the non-alphabet character, and then skip that character and continue to encode. Where and how should I put the if statement?


int main() {

  int i, txtLen=0, count;
  char text[100];

  printf("Please enter a text to RLE:\n");
  scanf("%s", text);

  while (text[i] != '\0') {
    txtLen++;
    i++;
  }

  for (i=0; i<txtLen; i++) {

    printf("%c", text[i]);
    count = 1;

    while (text[i+1] == text[i]){
      count++;
      i++;
    }

    if (count != 1) {
      printf("%d", count);
    }
  }
  return 0;
}

When I tried to put if statements, the input and output were like that:

Input: aa?aaabbb

Output: a2a3b3

Please do not give any suggestions or comments for other parts of my code.

Aucun commentaire:

Enregistrer un commentaire