将简单循环转换为 do-while

时间:2021-01-25 05:14:14

标签: c

如何将以下 while 循环转换为正确的 do-while 而不在第一次重复计算?

void ctype()
{
    char c;
    while ((c = getchar()) != '.')
        printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
    printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
}

到目前为止我所拥有的是:

void ctype()
// Print the letters up through the period, but quit on the period
{
    char c = getchar();
    do {
        printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
    } while ((c = getchar()) != '.') 
}

但是这个双getchar在第一项上。这样做的正确方法是什么?这几乎就像我想要在 while 循环中对 getchar() 进行后增量。


while 循环的示例输入/输出,当前正确:

$ run
.
'.' is not a letter.
$ run
Hello.
'H' is indeed a letter.
'e' is indeed a letter.
'l' is indeed a letter.
'l' is indeed a letter.
'o' is indeed a letter.
'.' is not a letter.

4 个答案:

答案 0 :(得分:8)

可以这样做:

char c;
do {
    c = getchar();
    printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
} while(c != '.');

一般情况下,您可以随时更改

while(<expr>) {
    // Body
}

do {
    if(<expr>) break;

    // Body
} while(1);

请注意,这只是为了简单地转换为 do-while。代码中还有其他缺陷。同时更正这些:

int c;
do {
    c = getchar();
    if(c == EOF) break;
    printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
} while(c != '.');

答案 1 :(得分:5)

检查 '.'EOF 的另一种方法,无需重复调用 getcharprintf

    int c;
    while ((c = getchar()) != EOF)
    {
        printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
        if(c == '.') break;
    }

答案 2 :(得分:2)

以下代码等价于使用while循环编写的代码:

void ctype()
{ 
    char c;
    do {
       c = getchar();
       printf("'%c' is %s a letter.\n", c, isalpha(c)? "indeed" : "not");
    } while (ch != '.');
}

答案 3 :(得分:1)

class CustomAdapter( var context: HomeFragment, retrofitData: ArrayList<Movdata>, private var OnClickInterface: OnClickInterface ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val TYPE_SECTION = 0 private val TYPE_MOVIE = 1 .... override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int) = when (i) { TYPE_SECTION -> SectionViewHolder(viewGroup.inflate(R.layout.section_header)) TYPE_MOVIE -> ItemViewHolder(viewGroup.inflate(R.layout.item_list)) else -> ItemViewHolder(viewGroup.inflate(R.layout.error_xml)) } .... override fun getItemViewType(position: Int) = when (retrofitData[position]) { is RecyclerItem.Genres -> TYPE_SECTION is RecyclerItem.Item -> TYPE_MOVIE } .... 没有任何问题,但通常 do - while 更具可读性,因此如果您有选择,请坚持使用后者。此外,在循环外对函数的初始调用通常也没有错,如果这能让循环代码更清晰。

此代码存在更多相关问题 - 您不检查 EOF,不丢弃换行符,并且在控制或循环条件内进行赋值。

最易读的形式可能是这样的:

while