0

我正在尝试读取网表(或文本)文件并将其分成单词。到目前为止,我已经尝试了下面的代码,但我无法摆脱错误。有任何想法吗?

我要阅读的文字是这样的:

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;
}
4

2 回答 2

2

差不多好了。stringstream用以下line内容初始化:

stringstream ss(line);

然后从中提取数据:

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

此外,您可能希望通过将路径传递给Netlistctor 来实际打开文件。

于 2020-02-24T12:20:04.900 回答
0

这是整个程序,它工作正常:

#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;
}

如果您正在从文件中读取,则可以直接读取该文件。您不需要阅读一行然后尝试阅读它。

你错过的东西:

  • 打开文件:std::ifstream netlist("netlist.txt");
  • 检查文件是否实际打开:!netlist.is_open()
  • 只需从流中读取:netlist >> componentName >> node1 >> node2 >> value; 注意:这也应该在ss您使用以下行初始化后才可以使用:std::stringstream ss(line);

有一个警告:从流中读取 std::string 时,您将始终读取一个单词。这适用于您的情况,但您需要注意这一点。

于 2020-02-24T12:31:30.293 回答