提问者:小点点

从文件中读取数据,然后对它们进行操作。将字符串转换为浮点


我有问题,但我不知道怎么解决。有人能帮帮我吗?问题。在文本文件中

1. 20.20
2. 3

我想从文件中获取数据,并使用它。我的代码:

int main() 
{
  string tp;
  float data_1 = 0, data_2 = 0, total = 0;

  std::fstream file;
  file.open("text.txt", ios::in);

  std::getline(file, tp);
  data_1 = std::stof(tp);

  std::getline(file, tp);
  data_2 = std::stof(tp);

  total = dat_1 * data_2;
  cout << "Total: " << total << endl;
}

在程序总数不是60.60,但它是需要的。问题在哪里?


共2个答案

匿名用户

#include <iostream>
#include <string>
#include <fstream>

int main(void)
{
    std::string tp;
    float data_1 = 0, data_2 = 0, total = 0;
    std::ifstream file("text.txt");

    std::getline(file, tp);
    data_1 = std::stof(tp);
    std::getline(file, tp);
    data_2 = std::stof(tp);
    total = data_1 * data_2; // you wrote dat_1 instead of data_1
    std::cout << total << std::endl;
    return (0);
}

匿名用户

首先,dat_1没有声明,它应该是data_1

然后,可以使用std::fixed指定点后的位数,使用std::setprecision指定位数。

cout << "Total: " << std::fixed << std::setprecision(2) << total << endl;

参考资料:

  • std::fixed,std::scientific,std::hexfloat,std::defaultfloat-cppreference.com
  • std::setprecision-cppreference.com

如果您确实希望打印60,60,而不是60.60,则可以使用std::replace更改字符。

#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <sstream>
using std::ios;
using std::cout;
using std::endl;

int main(){
    float total = 60.60;
    std::stringstream ss;
    ss << std::fixed << std::setprecision(2) << total << endl;
    std::string str = ss.str();
    std::replace(str.begin(), str.end(), '.', ',');
    cout << "Total: " << str << endl;
}