我正在尝试编写一个扫描文本文件的程序,并计算打开和关闭括号的数量以进行比较。然而到目前为止,我只设法计算一行中第一次出现括号。
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fileName;
fileName = fopen("/home/vagrant/Desktop/tests/t5", "r");
if (fileName != NULL)
{
int noOfOpenPar=0;
int noOfClosePar=0;
int noOfOpenSqr=0;
int noOfCloseSqr=0;
int noOfOpenCurl=0;
int noOfCloseCurl=0;
char lineOfText[80];
while (fgets(lineOfText, 80, fileName) != NULL)
{
if (strstr(lineOfText, "(") != NULL)
noOfOpenPar++;
if (strstr(lineOfText, ")") != NULL)
noOfClosePar++;
if (strstr(lineOfText, "[") != NULL)
noOfOpenSqr++;
if (strstr(lineOfText, "]") != NULL)
noOfCloseSqr++;
if (strstr(lineOfText, "{") != NULL)
noOfOpenCurl++;
if (strstr(lineOfText, "}") != NULL)
noOfCloseCurl++;
}
printf ("\nThe number of open parenthesies is %d and closed parenthesies %d\n", noOfOpenPar, noOfClosePar);
if (noOfOpenPar!=noOfClosePar)
printf("Number of open and closed parenthesies doesn't match\n");
printf ("\nThe number of open square brackets is %d and closed square brackets is %d\n", noOfOpenSqr, noOfCloseSqr);
if (noOfOpenSqr!=noOfCloseSqr)
printf("Number of open and closed square brackets doesn't match\n");
printf ("\nThe number of open curly brackets is %d and closed curly brackets is %d\n", noOfOpenCurl, noOfCloseCurl);
if (noOfOpenCurl!=noOfCloseCurl)
printf("Number of open and closed curly brackets doesn't match\n");
}
}
答案 0 :(得分:3)
你不能使用strstr()
,最好简单地遍历所有角色并检查它们。毕竟,你正在寻找1个字符的代币。
这样的东西反而在循环中:
for(const char *src = lineOfText; *src != '\0'; ++src)
{
const char here = *src;
if(here == '(')
++noOfOpenPar;
else if(here == ')')
++noOfClosePar;
else if ... /* more code here */
}
你明白了。你可以也依赖stdio的文件缓冲,一次只读一个字符,这会减少循环次数,但我认为这种方法更好。
当然,它也可以通过迭代包含要查找的字符及其相关计数器的结构数组来实现更多数据驱动。