C卡在一个无限循环中

C卡在一个无限循环中,c,loops,terminal,C,Loops,Terminal,我有一个简单的程序,我想测试一下自己,它基本上是从终端字符读取数据,并计算输入了多少小写字符 在我调用的函数中,它似乎永远在循环中运行 /* Create a function that reads the number of lower case letters from the user */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> void CopyMe(char []);

我有一个简单的程序,我想测试一下自己,它基本上是从终端字符读取数据,并计算输入了多少小写字符

在我调用的函数中,它似乎永远在循环中运行

/*
Create a function that reads the number of lower case letters from the user
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

void CopyMe(char []);

main ()
{
    char letters [100];
    int i = 0;
    do
    {
        letters [i++] = getchar();
    }
    while (letters [i-1] != '\n');
    letters [i-1] = '\0';

    CopyMe(letters);

    printf("Done \n");
    system("pause");
    return 0;
}

void CopyMe(char a[])
{
    int lowercase = 0;
    int i=0;
    while ( a[i] != '\0')
    {
        if (a[i] >= 'a' && a[i] <= 'z')
        {
            lowercase++;
        }
    }
    printf("Lowercase: %d \n", lowercase);
}

您忘了递增i变量…

您从未在CopyMe函数中递增i,因此while循环从未终止,始终在[0]上工作。

您没有在CopyMe中递增i:


使用调试器逐步完成循环。原因应该很快就会弄清楚。对于i=0,你不能出错;i每当循环似乎永远运行时,您最好检查循环的状态,并确定循环体中的任何内容是否会改变它。我的猜测如下:而字母[i-1]!='\n′;虽然我有时使用while循环,但我的同事和我自己都认为for循环更易于阅读、维护、理解,而且作为一种结构,它是避免愚蠢错误的更好工具。。。用于i=0;a[我]!='\0';++我或者,如果你坚持的话,为什么不增加指针a++?在CopyMe中…只用于循环
void CopyMe(char a[])
{
    int lowercase = 0;
    int i=0;
    while ( a[i] != '\0')
    {
        if (a[i] >= 'a' && a[i] <= 'z')
        {
            lowercase++;
        }
        i++; // <------- Don't forget about meeeeeee!!!
    }
    printf("Lowercase: %d \n", lowercase);
}