0

コマンドライン引数として指定されたファイル内の行で区切られた二項式のリストを読み込もうとしています。ファイルは次のようになります...

数字.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

「実際の」double変数値を正しく取得することに取り組んでいます。sscanf() も、x 係数の 1 つの先行ゼロ値を検出していません。これを修正するために 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;
}
4

1 に答える 1

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

このsscanfフォーマット文字列は次のように述べています。入力にはdouble値が含まれ、その後に空白が続き、その後に別のdouble値が続きます。

次のものを提供しますinput

 2.1x+1

ここにdouble値があり、その後に空白が続き、別のdouble値が表示されますか? もちろん違います。最初のdouble値の後に文字「x」が続きます。それは空白ではありません。

実際の入力が予想される入力と一致しないため、sscanf()入力の解析と戻り値の初期化に失敗します。からの戻り値を確認するとsscanf()、それがわかります。

sscanf()これを修正する方法の 1 つは、double 値の後に文字が続くことを伝えることです。

char char_value;

sscanf(input.c_str(), "%lf%c%lf", &complexnum.real, &char_value, &complexnum.imag);
于 2016-09-06T00:09:53.073 に答える