使用c++程序输出到.csv文件时出现问题

Issue in outputting into a .csv file using a c++ program

本文关键字:问题 文件 csv c++ 程序 输出 使用      更新时间:2023-10-16

我的程序将提示用户输入数字,程序将计算数字的乘积。我想以这种格式将我的数据存储到csv文件中"00:01AM/02/05/14.csv">

这是为了确保每次终止程序时,我都可以将数据存储到一个新的.csv文件中,而不是现有的.csv文件。但是我的程序没有输出到csv文件,因为一些错误,我无法修复。我不确定是什么原因造成了这个问题。这是我的代码:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>       
#include <string>        
#include <sstream> 
#include <time.h>
using namespace std;
string get_time();
string get_date();
int main()
{   //I can compile the codes but it is not outputting into a csv file 
    string date,time,out; 
    float a,b,c;
    ifstream indata;
    ofstream outdata;
    date=get_date();
    time=get_time();
    time=time+'/';
    out=time+date;//combines data&time into 12:01AM/02/05/14.csv string form
    cout<<out<<endl;
    //outputs the data into a csv file--but it is not working   
    outdata.open(out.c_str());
    outdata << "Num1,Num2,Answer" << endl;
    while (!(a ==-100))
   {    
    cout<<"Enter Num1:";
    cin>>a;
    if(a==-100)break;
    cout<<"Enter Num2:";
    cin>>b;
    c=a*b;
    outdata<<a<<","<<b<<","<<c<< endl;
   }    
    system("pause");
    return 0;
}
 string get_date()//converts date to string
{
   time_t now;
   char the_date[15];
   the_date[0] = '';
   now = time(NULL);
   if (now != -1)
   {
      strftime(the_date,15, "%d/%m/%y.csv", gmtime(&now));
   }
   return string(the_date);
}
string get_time()//converts time to stirng
{
   time_t currtime;
   struct tm * timeinfo;
   char the_time [12];
   time (&currtime);
   timeinfo = localtime (&currtime);
   strftime (the_time,12,"%I:%M%p",timeinfo);
   return string(the_time);
}   

您知道斜线是不能在文件名中使用的字符吗?Slash aka"/"是目录分隔符。

即使在Windows上,因为Windows试图至少与Unix兼容一点。

此外,这对你来说也是一堂很好的课。始终检查是否存在错误代码。您应该检查一下outdata.open是否成功。