解析二项式系数c ++

时间:2016-09-05 23:57:41

标签: c++ scanf binomial-coefficients

我试图读取二进制列表,在作为命令行参数给出的文件中用行分隔。该文件看起来像这样......

numbers.txt

2.1x+1
3x-5.3
-24.1x+24.7
0x-15.5
-12.3x+0

预期产出:

input: 2.1x+1
real: 2.1
imag: +1
input: 3x-5.3
real: 3
imag: -5.3
input: -24.1x+24.7
real: -24.1
imag: +24.7
input: 0x-15.5
real: 0
imag: -15.5
input: -12.3x+0
real: -12.3
imag: +0

我的输出:

input: 2.1x+1
real: 2.1
imag: 2.07545e-317
input: 3x-5.3
real: 3
imag: 2.07545e-317
input: -24.1x+24.7
real: -24.1
imag: 2.07545e-317
input: 0x-15.5
real: -24.1
imag: 2.07545e-317
input: -12.3x+0
real: -12.3
imag: 2.07545e-317

我正在获得真实的'双变量值正确。 sscanf()也没有检测到其中一个x系数的前导零值,我能用sscanf()解决这个问题吗?

#include <iostream>
#include <istream>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <vector>

using namespace std;

class binomial
{
public:
  double real;
  double imag;
  string usercmplx;
};

int main(int argc, char* argv[]){

  string word, input;
  vector <binomial> VecNums;
  binomial complexnum;

  // Inializes vector to size for speedup                                                                             
  VecNums.reserve(1000);

  ifstream file(argv[1]);

  // Parse txt file line by line                                                                                      
  while (file >> input) {
    // handle empty lines                                                                                             
    if (!input.empty()){

    // Saves the user input format                                                                                    
    complexnum.usercmplx = input;

    // This seperates the input into the real and imaginary parts                                                     
    sscanf(input.c_str(), "%lf %lf", &complexnum.real, &complexnum.imag);

    cout << "input: " << input << endl;
    cout << "real: " << complexnum.real << endl;
    cout << "imag: " <<complexnum.imag << endl;

    // Push binomials into Vector                                                                                       
    VecNums.push_back(complexnum);

    }
  }
  return 0;
}

1 个答案:

答案 0 :(得分:0)

sscanf(input.c_str(), "%lf %lf", &complexnum.real, &complexnum.imag);

sscanf格式字符串指出:输入包含double值,后跟一些空格,后跟另一个double值。

您提供以下input

 2.1x+1

您是否在此处看到double值,后跟一些空格和另一个double值?当然不是。第一个double值后跟字符&#39; x&#39;。那不是空白。

由于实际输入与预期输入不匹配,sscanf()无法解析输入并初始化返回的值。如果您从sscanf()检查返回值,您就会知道。

解决此问题的方法之一是告诉sscanf()字符是否跟随双值。

char char_value;

sscanf(input.c_str(), "%lf%c%lf", &complexnum.real, &char_value, &complexnum.imag);