sscanf在将字符串拆分为double值时失败

时间:2015-05-09 22:34:38

标签: c++ c scanf

我不知道我在这里犯了什么错误。但是sscanf并没有填满我的双数组(第一个索引)中的值。这是代码

int main() {
    int n = 0;
    cout << "Enter the number of equations" << endl;
    cin >> n;

    string coeffData;
    string powerData;
    double m_coeff_X[5] = {0.0,0.0,0.0,0.0,0.0};
    double m_coeff_Y[5] = {0.0,0.0,0.0,0.0,0.0};
    double m_coeff_Z[5] = {0.0,0.0,0.0,0.0,0.0};
    double m_coeff_V[5] = {0.0,0.0,0.0,0.0,0.0};
    double m_coeff_W[5] = {0.0,0.0,0.0,0.0,0.0};
    double m_const[5] = {0.0,0.0,0.0,0.0,0.0};

    for (int i = 0; i < n; i++) {
        cout << "Enter the coefficients for Number " << i+1 <<
                " equation. x,y,z,v,w (separated by commas)" << endl;
        cin >> coeffData;

        if (sscanf(coeffData.c_str(), "%f,%f,%f,%f,%f", 
            &m_coeff_X[i], &m_coeff_Y[i], &m_coeff_Z[i],
            &m_coeff_V[i], &m_coeff_W[i]) == 1) {
            cout << "value was ok";
        } else {
            cout << "value was not ok";
        }
        cout << m_coeff_X[i] << endl;
        cout << m_coeff_Y[i] << endl;
        cout << m_coeff_Z[i] << endl;
        cout << m_coeff_V[i] << endl;
        cout << m_coeff_W[i] << endl;
    }
    return 0;
}

我暂时只运行一次循环。这意味着i = 0,那就是所有..

输出结果为:

Enter the coefficients for Number 1 equation. x,y,z,v,w (separated by commas)
1.0,2.0,3.0,4.0,5.0
value was not ok
5.26354e-315
5.30499e-315
5.32571e-315
5.34643e-315
5.3568e-315  

编辑:感谢您提醒我它是%lf但不是%f。我是这样做的,但是正在玩代码。解决这个问题后,我得到了这个输出:

Enter the coefficients for Number 1 equation. x,y,z,v,w (separated by commas)
1.0,2.0,3.0,4.0,5.0
value was not ok
1
2
3
4
5

我首先这样做,事实是,当我打印这些双打时,它们打印为整数,我很困惑为什么会这样,我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

对于double,您需要使用%lf而不是%f

答案 1 :(得分:2)

sscanf doubles使用的格式错误,%lf而不是%f。在启用警告的情况下进行编译(例如使用g++ -Wall -W)会优雅地捕获此语法错误。 sscanf()按照指示解析浮点数,并将它们作为floats存储到程序实际用作doubles的内存中。这会调用未定义的行为。

您的程序可能会崩溃。这里似乎在这些double变量中存储无意义的值。更准确地说,它只修改double变量的一半字节。 floatsdoubles通常在内存中有不同的表示形式。

此外,此sscanf()调用的返回值应与5进行比较,而不是1sscanf返回成功转换的字段数。这就是您的计划输出value was not ok

的原因

关于输出,数字输出像整数一样,因为它们具有整数值。您可以使用snprintf()控制将数字转换为字符串的方式。这样做是一致的,因为您也使用sscanf()。存在一些更复杂的IMHO错误的API来控制iostream和<<运算符的转换。我会强烈反对这些因为它们对cout的副作用不容易回复。