将简单循环转换为 do-while

标签 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是第一项。这样做的正确方法是什么?这几乎就像我想要在 getchar() 上的等价的后增量在while循环中。
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.

最佳答案

可以这样做:

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 != '.');

关于将简单循环转换为 do-while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65879334/

相关文章:

c - Linux 生成文件示例

c - Linux 中 TCP 连接异常缓慢

c++ - 读取二进制结构数据

c - 三元运算符的奇怪枚举行为

c - 在互联网上传输数据时如何使用asn.1?

c - 如何测量在 Pentium 4 处理器上运行时 C 算法消耗的功率?

C程序结构错误从int分配类型结构节点

c - 哈希表搜索,命令提示奇怪的错误

java - 为什么我不能不等待就将 int 从 java 发送到 C?

c++ - -ffast-math 可以安全地用于典型项目吗?