大家好,所以我编写了这个程序,其目的是打开一个文件并读取其中有多少个字符并打印出最多和最少字符的行。我把它变成了两个函数,一个用于最大行“最大线”功能工作得很好,但是我输错了最小的输出。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char f_view[150];
void ShowResults();
int leastsymbols();
int mostsymbols();
int main(){
ShowResults();
return 0;
}
int mostsymbols(){
FILE *fp;
fp=fopen(f_view, "r");
if(fp==NULL){
printf("Error\n");
exit(-1);
}
int lineNO=1;
int c;
int currCount=0;
int highestCount=0;
int highestline=0;
while ((c = getc(fp)) != EOF){
if (c == '\n') {
currCount=0;
lineNO++;
}
if (c != '\n' && c != '\t' && c!= ' ') {
currCount++;
if(currCount>highestCount){
highestCount=currCount;
if(lineNO>highestline){
highestline=lineNO;
}
}
}
}
fclose(fp);
return highestline;
}
int leastsymbols()
{
FILE *fp;
fp = fopen(f_view, "r");
if (fp == NULL)
{
printf("Could not open file \n");
exit(-1);
}
int c;
int lineNO = 1;
int currCount=0;
int leastLine=0;
int leastCount=1000;//assuming that a line in a file can not be longer
//than 1000 characters
while ((c = getc(fp)) != EOF){
if (c == '\n'){
currCount = 0;
lineNO++;
}
if (c != '\n' && c != '\t' && c!= ' ') {
currCount++;
}
if(currCount<leastCount){
leastCount=currCount;
leastLine=lineNO;
}
}
fclose(fp);
return leastLine;
}
void ShowResults()
{
FILE *fptr;
char *fix;
char c;
char openFile[1024];
printf("Type the destination to the *.c file or the file name.\n");
//the user has to enter a .C file
while(f_view[strlen(f_view) - 2] != '.' && f_view[strlen(f_view) - 1]
!= 'c')
{
fgets(f_view, 150, stdin);
fix = strchr(f_view, '\n');
if(fix != 0)
*fix = 0;
}
if((fptr = fopen(f_view, "r")) == NULL)
{
printf("Cannot open file !\n");
exit(-1);
}
int highestLine;
int lowestLine;
while (fgets(openFile, 1024, fptr))
{
highestLine=mostsymbols();
lowestLine=leastsymbols();
}
printf("Line %d has the most symbols.\n",highestLine);
printf("Line %d has the least symbols.\n",lowestLine);
fclose(fptr);
return ;
}
答案 0 :(得分:1)
我修复了我的程序谢谢。:)
while ((c = getc(fp)) != EOF){
if(c == '\n' && currCount<leastCount){
leastCount=currCount;
leastLine=lineNO;
}
if(c=='\n'){
currCount = 0;
lineNO++;
}
if (c != '\n' && c != '\t' && c!= ' ') {
currCount++;
}
}
答案 1 :(得分:0)
当您转到下一行时将此检查移至
if(currCount<leastCount){
leastCount=currCount;
leastLine=lineNO;
}
您的展示位置错误,因为第一次迭代时currCount仍为1或0,具体取决于该行的第一个字符,因此它是最小的,这适用于您阅读的每一个新行