文件setprecision c ++代码

use*_*262 5 c++ file

我在C++中使用了这个代码正常工作,首先它要求用户输入文件名,然后在该文件中保存一些数字.

但我想要做的是保存两位小数的数字,例如用户类型2,我想保存数字2,但有两个小数位 2.00.

有关如何做到这一点的任何想法?

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
  double num;
  double data;
  string fileName = " ";
  cout << "File name: " << endl;
  getline(cin, fileName);
  cout << "How many numbers do you want to insert? ";
  cin >> num;
  for (int i = 1; i <= num; i++) {
    ofstream myfile;
    myfile.open(fileName.c_str(), ios::app);
    cout << "Num " << i << ": ";
    cin >> data;
    myfile << data << setprecision(3) << endl;
    myfile.close();
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 9

好的,你需要setprecision在写入数据之前使用.

我还会将文件的打开和关闭移出循环(myfile当然,这也是声明,因为它通常是一个相当"重"的操作来打开和关闭这样的循环内的文件.

这是一个有效的小演示:

#include <iostream>
#include <fstream>
#include <iomanip>

int main()
{
    std::ofstream f("a.txt", std::ios::app);
    double d = 3.1415926;

    f << "Test 1 " << std::setprecision(5) << d << std::endl;

    f << "Test 2 " << d << std::endl;

    f << std::setprecision(7);
    f << "Test 3 " << d << std::endl;

    f.precision(3); 
    f << "Test 3 " << d << std::endl;

    f.close();


}
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您的号码是例如3.0,那么您还需要std::fixed.例如,如果我们这样做:

    f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl;
Run Code Online (Sandbox Code Playgroud)

它会显示3.00000