c - 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
请不要对我的代码的其他部分提出任何建议或意见。
解决方案
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;
}
推荐阅读
- php - 将文本从CKEditor保存到php中的phpobjects时出现奇怪的行为
- r - 数据整理——将 n 步列转置为 n 行
- node.js - 未捕获的引用错误要求未定义
- swift - >.. 作为 Swift 中的后缀
- ruby-on-rails - ActionController::UnknownFormat: 新用户索引
- javascript - Leaflet L.geoJSON 可拖动
- arrays - 将目录名称和大小读入关联数组
- anaconda - 运行源激活
在 Anaconda Promt 中失败 - snowflake-cloud-data-platform - 列不匹配选项的错误在 snowsql 中不起作用
- list - 如何过滤列表