我有问题,但我不知道怎么解决。有人能帮帮我吗?问题。在文本文件中
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,但它是需要的。问题在哪里?
#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;
参考资料:
如果您确实希望打印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;
}