逐行读取文本文件并计算比较运算符

时间:2017-03-19 20:19:20

标签: c++ file

所以例如我有一个带有propper c ++代码的.txt文件。我想计算使用了多少比较运算符(例如!=,< =)。我通过char读char来找出它是如何做到的(参见下面的代码),但我无法弄清楚如何逐行阅读。也许有人可以给我一个提示?

#include <fstream>
#include <iostream>
using namespace std;

int main(){

fstream fin ("file.txt", ios::in);
bool flag=false;
char a;
int count=0;
fin.get(a);

while(fin)
{
    if(!flag)
    {
        if(a=='=' || a=='!' || a=='<' || a=='>')
        {
            flag=true;
        }
    }
    else
    {

        if(a=='=')
        {
            count++;
            flag=false;
        }
        else flag=false;
    }
    fin.get(a);
}
fin.close();
cout<<"The number of comparison operators in this file: "<<count<<endl;

return 0;
}

2 个答案:

答案 0 :(得分:1)

您的某些运算符不是字符,例如==和&lt; =两个字符,因此您必须将它们作为字符串进行比较,您能告诉我有关您的文件结构的更多信息吗?也许我可以给你一个更好的解决方案。

以下是您可能尝试的解决方案

void main()
{
fstream fin("file.txt", ios::in);
bool flag = false;
char a;
char b;
int count = 0;
fin.get(a);

while (fin)
{
    if (!flag)
    {
        if (a == '<' || a == '>')
        {
            fin.get(b);
            if (b!='>' && b!='<')
            count++;
        }
        else if (a == '!' || a == '=')
        {
            fin.get(b);
            if (b == '=')
                count++;
        }
    }
    fin.get(a);
}
fin.close();
cout << "The number of comparison operators in this file: " << count << endl;

逐行解决方案

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void main()
{
    fstream fin("file.txt", ios::in);
    string s = "";
    int count = 0;
    while (fin)
    {
        getline(fin, s);
        for (int i = 0; i < s.length()-1; i++)
        {
            if (s[i]== '<' || s[i] == '>')
            {
                if (s[i + 1] != '>' && s[i + 1] != '<' && s[i - 1] != '>' && s[i - 1] != '<')
                {
                    count++;
                }
            }
            else if (s[i] == '!' || s[i] == '=')
            {
                if (s[i + 1] == '=')
                {
                    count++;
                }
            }
        }
    }
    fin.close();
    cout << "The number of comparison operators in this file: " << count << endl;
    cout << endl << endl;
    system("pause");
}

答案 1 :(得分:0)

逐行读取或char取char之间没有什么大的区别,你只需要两个循环,一个用于读取行,第二个用于处理该行char by char几乎与处理整个文件的方式完全相同。