SSCANF在将字符串分解为双值时未能通过

sscanf failing on splitting string to double values

本文关键字:字符串 分解 SSCANF      更新时间:2023-10-16

我不知道我在这里犯了什么错误。但是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

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

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

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

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

的原因

关于输出,数字像整数一样输出,因为它们具有积分值。您可以控制使用snprintf()将数字转换为字符串的方式。这样做将是一致的,因为您也使用sscanf()。存在一些更详细的和恕我直言的API,可以用iostreams和<<操作员控制转换。我会强烈建议这些问题,因为它们对cout的副作用并不容易恢复。

double您需要使用%lf not%f