【发布时间】:2015-07-20 15:55:33
【问题描述】:
我不知道我在这里犯了什么错误。但是 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 应该返回“5”(找到的#/项目),而不是“1”。也使用 "%lf" 表示 "double" (和 "%f" 表示浮点数)。