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();
}
我正在尝试计算文件中的字母和数字的数量,但它对于数字不起作用,然后我认为我不确定如何正确处理声明而不是浪费计数。
我会感激任何帮助。
答案 0 :(得分:0)
Thx伙伴我用fgetc做了一切现在都有效。
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);
答案 1 :(得分:-1)
由于该程序每行只检查50个字符,因此该程序不太可能准确计算任何内容。
我建议改变:
while (fgets(buffer, 1000, pFile) != NULL)
为:
for (int i = 0; buffer[i] != '\0'; i++)