将fstream转换为float
Converting fstream to float
我正在尝试读取文件:
A = 10
B = 20.009
C为20.09,30.09
转换遇到的float/int值的代码是:
int main ()
{
fstream file1, file2;
string line;
int N;
float W;
file1.open("input.txt");
file2.open("output.txt");
if (file1)
{
while (getline( file1, line ))
{
if(line[0] == 'A')
{
file1 >> W;
cout << "A ="<<W;
}
else if(line[0] == 'B')
{
file1 >> W;
cout << W;
}
}
file1.close();
}
else cout << "Can't open filen";
return 0;
}
但我最终得到W = 0。我哪里做错了?我必须使用fscanf吗??
在第一次调用getline之后,文件现在指向A行和B行之间的换行符。当您尝试提取浮点数时,它不会看到任何看起来像浮点值的东西,它会遇到换行符并退出尝试。
您需要解析您读入line变量的每一行,或者使用操作符>>直接从文件中解析它,就像您试图处理浮点值一样。
相关文章:
- 没有合适的构造函数可以从"float"转换为"_D3DCOLORVALUE"
- 错误:无法将"float*"转换为"float"
- 有没有一种优雅的方法可以将矢量<复杂<float>>转换为矢量<short>?
- MBED RTOS将Float转换为字符串/字符阵列
- 错误:无法将参数"1"的"float*"转换为"float"
- 有没有快速的方法可以将std::vector<std::vector<float>>转换为std::vector<float2>?
- 将 const float* 转换为 std::array<float, ...>
- 当float转换为int时,此代码中是如何/为什么进行缩小的
- Arduino 无法在初始化时将'float'转换为'const char*'
- C++11自动.从float转换为long
- g++ 在不使用 -Wconvert 的情况下将 double/float 转换为无符号整数时发出警告
- 从 std::vector<std::vector<float>> 转换为 float**
- 在opencv中将垫子转换为矢量<float>和矢量<float>转换为垫子
- 代码一直说:“[错误]无法将参数'1'的'float*'转换为'float'到'void test(flo
- 从'float'转换为'LONG'需要缩小转换范围
- 错误:初始化时无法将'float*'转换为"qreal* {aka double*}"
- Int16_t到float转换的奇怪
- 使用JNI将float*转换为jfloatArray
- 将google::p rotobuf::RepeatedField<float>转换为浮动
- 将float转换为int时的奇怪行为