从文件中读取整数,中间有一个字符串

Reading integers from file, with a string in between

本文关键字:中间 有一个 字符串 整数 文件 读取      更新时间:2023-10-16

我有一个像这样的输入文件:

3 2
5 1
3 0
XXX
2 1
3 0

我需要分别读取每个整数,将其放入多项式中。"XXX"表示第二个多项式开始的位置。根据上面的例子,第一个多项式将是3x^2 + 5x^1 + 3x^0,第二个多项式将是2x^1 + 3x^0。

#include <iostream>
#include <iomanip>
#include <fstream>
#include "PolytermsP.h"
using namespace std;
int main()
{
    // This will be an int
    coefType coef;
    // This will be an int
    exponentType exponent;
    // Polynomials
    Poly a,b,remainder;
    // After "XXX", I want this to be true
    bool doneWithA = false;
    // input/output files
    ifstream input( "testfile1.txt" );
    ofstream output( "output.txt" );
    // Get the coefficient and exponent from the input file
    input >> coef >> exponent;
    // Make a term in polynomail a
    a.setCoef( coef, exponent );

    while( input )
    {
        if( input >> coef >> exponent )
        {
            if( doneWithA )
            {
                // We passed "XXX" so start putting terms into polynomial B instead of A
                b.setCoef( exponent, coef );
            } else {
                // Put terms into polynomail A
                a.setCoef( exponent, coef );
            }
        }
        else
        {
            // Ran into "XXX"
            doneWithA = true;
        }
    }

我遇到的问题是多项式A的值(在XXX之前)正在工作,但不适合b。

我要问的是:我如何使它,所以当我遇到"XXX",我可以设置"doneWithA"为真,并继续阅读文件后"XXX"?

我会把它们放在单独的循环中,因为你知道有两个,而且只有两个:

coefType coef; // This will be an int
exponentType exponent; // This will be an int
Poly a,b;
ifstream input( "testfile1.txt" );
while( input >> coef >> exponent )
    a.setCoef( exponent, coef );
input.clear();
input.ignore(10, 'n');
while( input >> coef >> exponent )
    b.setCoef( exponent, coef );
//other stuff

我认为最简单的方法是始终将输入读取为字符串,然后应用atoi(), http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/如果这个函数失败,那么你就得到了一个不是数字的字符串。"xxx"。

    const string separator("XXX");
    while(input){
        string line;
        getline(input,line);
        if(line == separator)
            doneWithA = true;
        else {
            istringstream input(line);
            if(input >> coef >> exponent){
                if(doneWithA)
                    b.setCoef( coef, exponent );
                else
                    a.setCoef( coef, exponent );
            }
        }
    }
相关文章: