二进制函数c++的系数解析
Parse Coefficients of Binomials c++
我正在尝试读取二进制数列表,这些二进制数在作为命令行参数的文件中以行分隔。文件看起来像这样。。。
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系数的前导零值,我可以对sscann((做些什么来解决这个问题吗?
#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;
}
sscanf(input.c_str(), "%lf %lf", &complexnum.real, &complexnum.imag);
此sscanf
格式字符串声明:输入包含一个double
值,后面跟着一些空白,后面跟着另一个double
值。
您提供以下input
:
2.1x+1
您在这里看到一个double
值,后面跟着一些空格,还有另一个double
值吗?当然不是。第一个double
值后面跟有字符"x"。这不是空白。
由于实际输入与预期输入不匹配,sscanf()
无法解析输入并初始化返回值。如果您检查sscanf()
的返回值,您就会知道这一点。
解决此问题的方法之一是告诉sscanf()
一个字符跟在双值后面。
char char_value;
sscanf(input.c_str(), "%lf%c%lf", &complexnum.real, &char_value, &complexnum.imag);
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗