将fstream转换为float

Converting fstream to float

本文关键字:float 转换 fstream      更新时间:2023-10-16

我正在尝试读取文件:

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变量的每一行,或者使用操作符>>直接从文件中解析它,就像您试图处理浮点值一样。