【问题标题】:Read data from file and then working witch them. Converting string to float从文件中读取数据,然后使用它们。将字符串转换为浮点数
【发布时间】:2021-06-16 22:36:15
【问题描述】:

我有问题,但我不知道如何解决。有人可以帮助我吗? 问题。在文本文件中

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,但它需要。问题出在哪里?

【问题讨论】:

  • 文本文件怎么了?那些是行号吗?该文件实际上是否在每行的开头包含一个数字?或者这只是 SO 的格式问题?另外:你得到什么输出?您是否尝试使用调试器?如果不是,这是一个学习如何使用的好机会。
  • 你真的想要60,60,而不是60.60
  • 您的text.txt 是否真的包含1.2.
  • 在文本文件中是 2 行。第一行是 20.20,第二行是 3。我想要 60.60。
  • 你得到了什么总数[原文如此,这是一个产品而不是总数]?

标签: c++ string file


【解决方案1】:

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

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

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

参考资料:

如果你真的想打印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;
}

【讨论】:

  • 不,我想要 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);
}

【讨论】:

  • 在程序中出现错误。错误:“stof”不是“std”的成员,它位于写入 data_1 = std::stof(tp); 的行
猜你喜欢
  • 1970-01-01
  • 2019-08-21
  • 2013-01-07
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
相关资源
最近更新 更多