C从文件中计算数字和字母的数量 intmain() { //定义我们期望的最大值为1000 //每行读取的字符数。 字符缓冲区[1000]; 文件*pFile; 字符数=0; chars=0; //打开文件进行读取 pFile=fopen(“vstup.txt”,“r”); //如果发生错误,fopen返回1 如果(!pFile) printf(“错误:无法读取文件\n”); while(fgets(缓冲区,1000,pFile)!=NULL) { printf(“%s”,缓冲区); 对于(int i=0;i='0'&&buffer[i]='A'&&buffer[i]='A'&&buffer[i]

C从文件中计算数字和字母的数量 intmain() { //定义我们期望的最大值为1000 //每行读取的字符数。 字符缓冲区[1000]; 文件*pFile; 字符数=0; chars=0; //打开文件进行读取 pFile=fopen(“vstup.txt”,“r”); //如果发生错误,fopen返回1 如果(!pFile) printf(“错误:无法读取文件\n”); while(fgets(缓冲区,1000,pFile)!=NULL) { printf(“%s”,缓冲区); 对于(int i=0;i='0'&&buffer[i]='A'&&buffer[i]='A'&&buffer[i],c,file,C,File,,由于该程序每行仅检查50个字符,因此该程序不太可能准确计数 我建议改变: int main() { // Defining that we only expect there to be a maximum of 1,000 // characters per lines read. char buffer[1000]; FILE *pFile; char numbers = 0; char chars = 0; // Opens t

,由于该程序每行仅检查50个字符,因此该程序不太可能准确计数

我建议改变:

int main()
{

    // Defining that we only expect there to be a maximum of 1,000
    // characters per lines read.
    char buffer[1000];
    FILE *pFile;
    char numbers = 0;
    char chars = 0;

    // Opens the file for reading
    pFile = fopen("vstup.txt", "r");

    // fopen returns 1 if an error occurred 
    if (!pFile)
        printf("Error : Couldn't Read the File\n");


    while (fgets(buffer, 1000, pFile) != NULL)
    {

        printf("%s", buffer);

        for (int i = 0; i < 50; i++)
        {
            if (buffer[i] >= '0' && buffer[i] <= '9')
            numbers++;

            if ((buffer[i] >= 'A' && buffer[i] <= 'Z') || (buffer[i] >= 'a' && buffer[i] <= 'z'))
                chars++;
        }

    }


    printf("\nSuccess Reading from File\n");
    printf("\nNum of numbers %d",numbers);
    printf("\nNum of letters %d", chars);

    // Closes the text file
    if (fclose(pFile) != 0)
        printf("Error : File Not Closed\n");

    getchar();

}
致:


Thx伙计们,我和fgetc一起做的,现在一切都正常了

for (int i = 0; buffer[i] != '\0'; i++)
do
{
c=fgetc(pFile);
if(feof(pFile))
{
打破
}
printf(“%c”,c);

如果(c>='0'&&c='A'&&c='A'&&c为什么数字和字符计数器是
char
类型而不是
integer
?使用
isalpha
isdigit
中定义的(int i=0;i<50;i++)
此循环假设每行正好有50个字符,但行可能有任意长度。使用
缓冲区[i]!='\0'
作为条件。顺便说一下,在这种情况下,您可以不用读取行(因此可以猜测最大行长)通过使用
fgetc
逐字符读取输入字符。您可以计算数字,而不是数字。这是一条注释,而不是答案对我来说似乎是答案。您建议的更改是针对(int i=0;i<50;i++)的
,而不是
,而(fgets(buffer,1000,pFile)!=NULL)
,并且它不正确,应该是针对(int i=0;buffer[i]的
!='\0';i++)
oops!复制粘贴错误,谢谢。也许我应该在提交下一个答案之前喝上当天的第一杯咖啡:-P
for (int i = 0; buffer[i] != '\0'; i++)
do
    {
        c = fgetc(pFile);
        if (feof(pFile))
        {
            break;
        }
        printf("%c", c);
        if (c >= '0' && c <= '9')
            numbers++;

        if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
            chars++;
    } while (1);