用c++语言搜索文件中的单词

Searching words in a file with C++ language

本文关键字:单词 文件 搜索 c++ 语言      更新时间:2023-10-16

我正在编辑我的帖子与我目前取得的进展。现在我要做的是:

  1. 从不带星号(*)的第一行读取文本文件,也就是以数字1开头的行,直到文件的末尾
  2. 当有"空格"而不是">sa0"(第六列)时,在变量上加一个@。并将下一个字符串放在下一个变量(即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. 不显示带有astherisc的最后一行之后的第一行。
  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这样的东西会让工作变得非常容易。

如果你坚持不使用解析器生成器或类似的工具,你至少可以使用正则表达式来帮助你。