首页 > 解决方案 > if 条件不成立时取消循环

问题描述

我正在尝试编写一个执行运行长度编码的程序。我编写了程序,但是当输入中有非字母字符时,我想取消整个循环。我的意思是,它应该给出类似“输入无效!”的输出。

我尝试了几个 if 条件,但每次它都将字母字符编码到非字母字符,然后跳过该字符并继续编码。我应该在哪里以及如何放置 if 语句?


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;
}

当我尝试放置 if 语句时,输入和输出是这样的:

输入: aa?aaabbb

输出: a2a3b3

请不要对我的代码的其他部分提出任何建议或意见。

标签: cloopsif-statement

解决方案


int main(void) {
  int i, txtLen=0, count;
  char text[100];

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

  while (text[i] != '\0') {
// check if the value of each char if it is within the alphabetical range of char
    if((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z')) {
      printf("False Format\n");
      break;
    }
    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;
}


推荐阅读