用C++语言在文件中搜索单词

Searching words in a file with C++ language

我正在编辑 post 我目前取得的进展。嗯,我现在想做的是:

  1. 从不带星号 (*) 的第一行(即以数字 1 开头的行)到文件末尾读取文本文件
  2. 当有 "blank space" 而不是“>sa0”(第 6 列)时,在变量上放置一个 @。并将下一个字符串放在下一个变量(又名 fsa1)
  3. 逐行打印给用户。

我目前的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    string line, netlist;
    int address, fout, fin;
    string name, type, fsa0, fsa1;

    cout << "Wich Netlist you want to use?" << endl;
    cin >> netlist;

    ifstream file(netlist.c_str());

        if (file.is_open())
        {
             do{

                getline(file, line);

             } while ( line[0] == '*' );


                file >> address >> name >> type >> fout >> fin >> fsa0;
                if (fsa0 != ">sa0") { fsa1 = fsa0; fsa0 = "@"; } else { file >> fsa1; }
                cout << address <<  " " << name << " " << type << " " << fout << " " << fin << " " << fsa0 << " " << fsa1 << endl;



        } else { cout << "File not found" << endl; }

             file.close();

    return 0;
}

发现的问题:

  1. 不显示带有 astheresc 的最后一行之后的第一行。
  2. 只显示第二行没有显示所有行。

我正在尝试读取的文本文件:

*c17 iscas example (to test conversion program only)
*---------------------------------------------------
*
*
*  total number of lines in the netlist ..............    17
*  simplistically reduced equivalent fault set size =     22
*        lines from primary input  gates .......     5
*        lines from primary output gates .......     2
*        lines from interior gate outputs ......     4
*        lines from **     3 ** fanout stems ...     6
*
*        avg_fanin  =  2.00,     max_fanin  =  2
*        avg_fanout =  2.00,     max_fanout =  2
*
*
*
*
*
    1     1gat inpt    1   0      >sa1
    2     2gat inpt    1   0      >sa1
    3     3gat inpt    2   0 >sa0 >sa1
    8     8fan from     3gat      >sa1
    9     9fan from     3gat      >sa1
    6     6gat inpt    1   0      >sa1
    7     7gat inpt    1   0      >sa1
   10    10gat nand    1   2      >sa1
     1     8
   11    11gat nand    2   2 >sa0 >sa1
     9     6
   14    14fan from    11gat      >sa1
   15    15fan from    11gat      >sa1
   16    16gat nand    2   2 >sa0 >sa1
     2    14
   20    20fan from    16gat      >sa1
   21    21fan from    16gat      >sa1
   19    19gat nand    1   2      >sa1
    15     7
   22    22gat nand    0   2 >sa0 >sa1
    10    20
   23    23gat nand    0   2 >sa0 >sa1
    21    19

另外,你们能给我一些提示,告诉我如何处理这些仅包含两个整数的行,就像最后一个吗?

谢谢大家。感谢所有帮助。

至少在我看来,您的处理方式是错误的。我将从阅读一行输入开始。然后检查该行上有多少项目。然后适当地解析行中的项目。

除非您绝对打算自己用纯 C++ 来完成这项工作,否则 AWK 或 yacc 之类的东西将使工作变得非常容易。

如果您坚持在没有解析器生成器或类似工具的情况下这样做,您至少可以使用正则表达式来提供一些帮助。