我正在学习用C++编写代码,并且正在做一些文件操作的示例。将文本数据另存为.txt文件时,将其发送到文件不会出现问题。
然而,我更进一步,在csv文件上进行了实验:
#include <iostream>
#include <string>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main ()
{
int num = 0;
fstream file;
string file_name;
cout << "Input file name: ";
cin>>file_name;
file.open(file_name.c_str());
if (file.fail())
{
cout << "Unable to open file - try again" << endl;
main ();
} else
{
file << "VALUE" << "\t" << "1/x" << "\t" << "sqrt" << endl;
while (num < 200)
{
file << num << "\t" << 1/num << "\t" << sqrt(num) << endl;
num ++;
}
file.close();
return 0;
}
}
当我检查文件时-只有标题:
我应该怎么做才能将这些数学运算的结果写入这个csv文件?
发布于 2019-11-13 03:33:52
请看我关于被零除的评论。另外,不要使用整型除法。变化
while (num < 200)
{
file << num << "\t" << 1/num << "\t" << sqrt(num) << endl;
num ++;
}
至
while(num < 200)
{
num++;
file << num << "\t" << 1.0 / num << "\t" << sqrt(num) << endl;
}
https://stackoverflow.com/questions/58829874
复制相似问题