0

ı'm trying to read a netlist(or text) file and seperate it to words. So far I have tried the code below but I cannot get rid of errors. Any ideas?

the text I am trying to read is like this:

V1 1 0 12
R1 1 2 1000
R2 2 0 2000
R3 2 0 2000
using namespace std; 

int main() {
    ifstream Netlist;

    string line;
    string componentName;
    int node1,node2;
    double value;
    while(getline(Netlist, line)) {
        stringstream ss(line>>componentName >> node1>> node2>>value);
        cout<<"Component name:" << componentName<< endl;
        cout<<"Node1:" << node1<< endl;
        cout<<"Node2:" << node2<< endl;
        cout<<"Value:" <<value << endl;
    }

    return 0;
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
sdcoders
  • 19
  • 2
  • 1
    seems to be code missing in your snippet. where do you open the file - Netlist? – AndersK Feb 24 '20 at 12:16
  • `stringstream ss(line>>componentName >> node1>> node2>>value);` is not valid. You probably meant: `stringstream ss(line); ss >>componentName >> node1>> node2>>value;` – ChrisMM Feb 24 '20 at 12:18
  • As a general remark, try to avoid ```using namespace std;```. See [this](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) thread for further information – sfun Feb 24 '20 at 12:34

2 Answers2

2

Almost there. Initialize the stringstream with the line contents:

stringstream ss(line);

And then pull data out of it:

ss >> componentName >> node1 >> node2 >> value;

Also, you probably wanted to actually open your file by passing a path to Netlist ctor.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
0

This is the whole program and it works fine:

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream netlist("netlist.txt");
    if (!netlist.is_open())
    {
        std::cerr << "Failed to open netlist.txt." << std::endl;
    }

    std::string componentName;
    int node1 = 0;
    int node2 = 0;
    double value = 0.0;
    while (netlist.good())
    {
        netlist >> componentName >> node1 >> node2 >> value;

        std::cout << "Component name: " << componentName << std::endl;
        std::cout << "Node1: " << node1 << std::endl;
        std::cout << "Node2: " << node2 << std::endl;
        std::cout << "Value: " << value << std::endl;
    }

    return 0;
}

If you are reading from a file, you can read the file directly. You do not need to read a line and then try to read that.

Things you missed:

  • opening the file: std::ifstream netlist("netlist.txt");
  • checking if the file is actually open: !netlist.is_open()
  • simply reading from the stream: netlist >> componentName >> node1 >> node2 >> value; Note: this should also just work with ss once you initialised it with line: std::stringstream ss(line);

There is one caveat: when reading std::string from a stream, you will always read one word. This works in your case, but you need to be mindful about that.

rioki
  • 5,988
  • 5
  • 32
  • 55