c - 是否可以使用 for 循环编写“else if”N 次?
问题描述
我正在编写一个作为 K&R 练习的 entab 程序。
练习 1-21。编写一个程序entab,用最少数量的制表符和空格替换空格字符串,以达到相同的间距。
我的解决方案是将每一行除以 N 个字符(where 1 tab == N whitespace
)并检查从最右边的字符到第一个字符是否是空白字符。
#include <stdio.h>
void entab(int n);
int main(void)
{
entab(8);
}
void entab(int n) // n should be at least 2
{
int c;
int i, j;
int temp[n];
while (1) {
// Collect n characters
// If there is EOF, print all privious character and terminate the while loop.
// If there is new line character, print all privious and current character, then continue the while loop again.
for (i = 0; i < n; ++i) {
temp[i] = getchar();
if (temp[i] == EOF) {
if (i > 0)
for (j = 0; j < i; ++j)
putchar(temp[j]);
break;
}
else if (temp[i] == '\n') {
for (j = 0; j <= i; ++j)
putchar(temp[j]);
break;
}
}
if (temp[i] == EOF)
break;
if (temp[i] == '\n')
continue;
// the temp array has exactly 8 characters without newline character and EOF indicator.
// check a continuity of the whitespace character and put the tab character at the right space.
if (temp[n-1] != ' ') {
for (i = 0; i <= n-1; ++i)
putchar(temp[i]);
}
for (j = n-2; j >= 0; --j) {
else if (temp[j] != ' ') {
for (i = 0; i <= j; ++i)
putchar(temp[i]);
putchar('\t');
}
}
else
putchar('\t');
}
}
这部分是有道理的,但在语法上是不允许的。但我必须使用循环语法,因为我希望程序输入任意数量的空白字符。
if (temp[n-1] != ' ') {
for (i = 0; i <= n-1; ++i)
putchar(temp[i]);
}
for (j = n-2; j >= 0; --j) {
else if (temp[j] != ' ') {
for (i = 0; i <= j; ++i)
putchar(temp[i]);
putchar('\t');
}
}
else
putchar('\t');
我尝试了一个类似函数的宏,但没有显着差异。这是不可能的吗?我应该考虑另一种设计或逻辑吗?
解决方案
推荐阅读
- c++ - 强制 clang 在此 C++ 代码片段上生成编译错误
- sql - 为什么 ISNULL 不生成“警告:空值被聚合或其他 SET 操作消除”。但是 CASE IS NULL 和 COALESCE 呢?
- html - 修复选择框选项中下拉菜单的宽度
- python - 检查 django 模型查询集中是否不存在
- html - sass 导入部分与非部分
- sql - 将连接输出从三个表连接保存到新表
- xamarin.forms - 列表视图中带有卡片/框架的页面(X.Forms 4.6+)
- c++ - 有没有办法将编译器标志从 SUB_DIRECTORY 传播到 CMake 中的整个项目?
- python - python中的模型训练和Golang中的模型运行,模型导入过程中的问题
- c - 发出一个简单的 HTTP 请求并阅读回复