[英]reading characters from a file using c code
我寫了一個C代碼來計算文件中沒有字符,單詞和行數。
代碼如下。
#include "stdio.h"
#include "conio.h"
#define FILE_NAME "abc.txt"
void main()
{
FILE *fr;
int noc = 0;
int now = 0;
int nol = 0;
char ch;
printf("hello world\n");
getch();
//clrscr();
fr = fopen("..\\abc.txt","r");
if(fr == NULL)
{
printf("\n error \n");
getch();
return;
}
ch = fgetc(fr);
while(ch != EOF)
{
printf("%c", ch);
noc++;
if(ch == ' ');
{
now++;
}
if(ch=='\n')
{
nol++;
now++;
}
ch=fgetc(fr);
}
fclose(fr);
printf("\n noc = %d now = %d nol = %d\n", noc, now, nol);
getch();
}
我的文件abc.txt如下。
Hello my friend.
How are you doing?
我得到以下輸出:
hello world
Hello my friend.
How are you doing?
noc = 38 now = 40 nol = 2
該代碼能夠正確讀取任何字符和行。 但是,它將每個字符視為一個單詞。 當不計算上面代碼中的單詞數時,我不明白我在哪里出錯。
詳細的解釋將不勝感激。
提前致謝。
if(ch == ' '); <------- see this (remove semicolon)
{
now++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.