读取整数对,直到文本输入文件中的换行符

Reading pairs of integers until newline in text input file

本文关键字:文件 输入 换行符 文本 整数 读取      更新时间:2023-10-16

嘿伙计们,所以我有一个问题。我想读取整数对(第一个是系数,第二个是指数),这些对中的每一个都是链表中的一个节点。我会继续用这些对填充链表,直到它在输入文本文件中看到换行符或 Enter 键。

下一行它将再次开始,因此输入文件将如下所示

-1 0 6 2 3 2 5 6 1 6
2 5 3 2 4 2 5 7 2 7

阅读后它将是两个不同的多项式,即

  • 多项式 1 = -1 + 6x^2 + 3x^2 + 5x^6 + x^6

  • 多项式 2 = 2x^5 + 3x^2 + 4x^2 + 5x^7 + 2x^7

或 2 个不同的链表,每个多项式一个。因为目前我的方式,如果我只是使用喜欢

while (infile >> coefficient >> exponent)
{
     polynomialA.listInsert(coefficient, exponent);
}

它将读取两行并创建一个很长的单个多项式。

编辑:对不起,我想我不清楚。问题是 - 如何使 ifstream 继续读取 intgers 对,直到它到达文本文件中的换行符。

您可以将其分成几行,然后是标记: 提示:将std::stringstreamstd::getline一起使用

std::string line;
std::getline(infile, line)  //Read the whole line
{
    std::stringstream ss(line);
    while(ss >> coefficient >> exponent)  //read the pairs
        polynomialA.listInsert(coefficient, exponent);
}
std::getline(infile, line)  //read another whole line
{
    std::stringstream ss(line);
    while(ss >> coefficient >> exponent)  //read the pairs
        polynomialB.listInsert(coefficient, exponent);
}

当然,以上可以用更好的方式写,但是,我会把它留给你。