2017-03-19 122 views
0

因此,例如,我有一个带有propper C++代码的.txt文件。我想统计已经使用了多少个比较运算符(例如!=,< =)。我想通过阅读字符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; 
} 

回答

1

你的一些运营商都没有字符,如==和< =两个字符,所以你必须将它们的比较结果为一个字符串,你能告诉我更多关于你的文件结构?也许我可以给你一个更好的解决方案。

这里是一个解决方案,你可以通过在线解决方案

#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"); 
} 
+0

所以例如我有这样txt文件: 'INT主() { INT一个; cin >> a;如果(a == 10) cout <<“宾果!”; if(a <=9 && a> = 4) cout <<“很好,但仍需要一些练习! if(a <=3 && a > = 1) cout <<“下次更好运!”; 如果(a <=0 || a> 10) cout <<“无效输入”; return 0; }' 输出结果是:6(仅计数<=,==和<=) – Jan4ezz

+0

是的,但它也从文件('cin.get')中读取char by char。我在想,如何逐行阅读(使用'getline(fin,s)',其中s是一个被读取的字符串)。所以我会从文本中读取一行,但我不知道如何比较该行中的每个单词来计算这些操作符? – Jan4ezz

+0

由于某种原因,它不能编译。首先它说main()必须返回int值(所以它应该是'int main()'),但是当我改变它并尝试运行这个程序时它会崩溃。 ''program.exe停止工作“但我不明白为什么 – Jan4ezz

0

有读数线之间的线或烧焦成炭没有大的区别尝试

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; 

行,你只需要两个循环,一个用于读取行,另一个用于处理该char char by char几乎完全相同的方式处理整个文件。

+0

或者也许人们可以getline()整行,然后相应地划分它吗?而你的答案是不解决实际问题如果你只是想告诉他**这不是一个很大的区别**那么你应该评论它。 – Weaboo