【问题标题】:Reading integers from file, with a string in between从文件中读取整数,中间有一个字符串
【发布时间】:2011-10-04 19:57:50
【问题描述】:

我有一个如下所示的输入文件:

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”设置为 true,并在“XXX”之后继续阅读文件?

【问题讨论】:

  • 文件格式是强加给你的吗?它看起来很不雅。如果你能改变它,每行有一个多项式会让事情变得容易得多。

标签: c++ input extract


【解决方案1】:

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

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

【讨论】:

  • clear错误但不要ignore行的其余数据,所以它会在下一个循环中立即失败。
  • 这正是我需要知道的。现在可以了,谢谢!
【解决方案2】:

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

【讨论】:

    【解决方案3】:
        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 );
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 2017-05-03
      • 2016-08-09
      相关资源
      最近更新 更多