我不知道我在这里犯了什么错误。但 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
我首先这样做了,问题是,当我打印这些 double 时,它们打印为整数,我很困惑为什么会这样,我在这里做错了什么?
最佳答案
您在 sscanf
中使用了错误的格式对于 doubles
,应该是%lf
而不是%f
。在启用警告的情况下进行编译,例如 g++ -Wall -W
会优雅地捕获这个语法错误。 sscanf()
按照指示解析 float 并将其存储为 floats
进入程序实际使用的内存 doubles
。这会调用未定义的行为。
你的程序可能会崩溃。这里似乎在这些 double
中存储了无意义的值。变量。更准确地说,它只修改 double
的一半字节。变量。 floats
和doubles
通常在内存中有不同的表示。
此外,这个sscanf()
的返回值调用应与 5
进行比较,不是1
。 sscanf
返回成功转换的字段数。这就是你的程序输出 value was not ok
的原因。 .
关于输出,数字输出像整数,因为它们具有整数值。您可以使用 snprintf()
控制将数字转换为字符串的方式。 。这样做是一致的,因为您使用 sscanf()
以及。存在一些更复杂且恕我直言构思不良的 API 来控制 iostream 和 <<
的转换。运算符(operator)。我强烈建议不要使用这些,因为它们对cout
有副作用。不容易恢复。
关于c++ - sscanf 无法将字符串拆分为 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30145750/