テキストファイルをスキャンし、比較のために開いている括弧と閉じた括弧の数を数えるプログラムを作成しようとしています。しかし、これまでのところ、1行目の括弧の最初の出現を数えただけでした。あなたはこのためにstrstr()
を使用することはできませんファイル内の大括弧の数を数えよう
#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");
}
}
ループがさらに必要です。または、文字ごとにファイルを読むことができます。 –
カウントするだけで一致するかどうかわかりません。 – BLUEPIXY