[英]Counting the amount 2 digit numbers in C
I have a slight problem with a program in which I have to count the amount of 2digit numbers in a text file. 我的程序有一个小问题,其中我必须计算文本文件中2位数字的数量。 The text file consists of both symbols(letters in this case) and numbers.
文本文件由符号(在这种情况下为字母)和数字组成。 This is what I got so far.
这就是我到目前为止所得到的。
int main ()
{
FILE *fr;
int digit;
char num[256];
fr = fopen ("tekst.txt","r");
if(fr==NULL)
printf("File cannot open");
return 0;
while (!feof(fr));
{
fscanf(fr,"%s",num);
printf("%s\n", num);
}
/*9
if(num==0)
digit=2;
else
for(digit=0;num!=0;num/=10,digit++);
printf("the amount of 2 digit numbers is:%d\n",digit);
*/
fclose(fr);
system("PAUSE");
return 0;
}
Can someone help me out? 有人可以帮我吗?
Do you come from python? 您来自python吗?
if(fr==NULL)
printf("File cannot open");
return 0;
translates to 转换为
if(fr==NULL)
printf("File cannot open");
return 0;
or rather 更确切地说
if(fr==NULL)
{
printf("File cannot open");
}
return 0;
so everything after the return 0
is obviously not executed, even if fr
is NULL
or not. 因此,即使
fr
是否为NULL
, return 0
之后的所有内容显然也不会执行。
This will count the two digit numbers in the file. 这将计算文件中的两位数字。 It will count "(37)" or " 37 " but not "07".
它将计为“(37)”或“ 37”,但不计为“ 07”。
To include numbers with leading zero change && iTens >= '1' && iTens <= '9'
to && iTens >= '0' && iTens <= '9'
. 要包括前导零变化
&& iTens >= '1' && iTens <= '9'
到&& iTens >= '0' && iTens <= '9'
。
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE *pf = NULL;
int iNumber = 0;
int iCount = 0;
int iHundreds = -1;
int iTens = -1;
int iOnes = -1;
int iEach = 0;
if ( ( pf = fopen ( "tekst.txt", "r")) == NULL) {
perror ( "could not open file\n");
return 1;
}
while ( ( iEach = fgetc ( pf)) != EOF) { // read a character until end of file
if ( iEach >= '0' && iEach <= '9') { //number
iHundreds = iTens; // for each digit read, move digits up the chain
iTens = iOnes;
iOnes = iEach;
}
else { // non number
if ( iHundreds == -1 // if iHundreds is not -1, more than two digits have been read
&& iTens >= '1' && iTens <= '9'// check that iTens and iOnes are in range
&& iOnes >= '0' && iOnes <= '9') {
iTens -= '0'; // convert character code to number, '3' to 3
iOnes -= '0';
iNumber = ( iTens * 10) + iOnes;
iCount++;
printf ( "%d\n", iNumber);
}
iHundreds = -1;
iTens = -1;
iOnes = -1;
}
}
printf ( "Counted %d two digit numbers\n", iCount);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.