Pergunta

I'm trying to write a program which outputs a lot of data in separate text files. I want the title of each file to be Poker_Log_timestamp_datestamp.txt However, it doesn't actually create the file, nor does it throw any errors!

Here's the code:

#include <fstream>
#include <iostream>
#include <ctime>
#include <string>
using namespace std;

int main(){
    char sdate[9];
    char stime[9];
    fstream log;
    _strdate_s(sdate);
    _strtime_s(stime);
    string filename = "Poker_Log_";
    filename.append(stime);
    filename.append("_");
    filename.append(sdate);
    filename.append(".txt");
    cout<<"Filename == "<<filename<<endl;
    log.open(filename.c_str());
    log<<"\n\nHuman won the tournament.\n";
    log.close();
    system("Pause");
}

How do I make this work? One other thing: If I comment out filename.append(stime) and filename.append(sdate), it works fine.

SOLVED :D The file name cant have any slashes or colons, so i replaced them both with dashes. Here is the working code:

#include <fstream>
#include <iostream>
#include <ctime>
#include <string>
#include <cstdio>

using namespace std;

int main(){
    char sdate[9];
    char stime[9];
    ofstream log;
    _strdate_s(sdate);
    _strtime_s(stime);
    string filename = "Poker_Log_";
    filename.append(stime);
    filename.append("_");
    filename.append(sdate);
    filename.append(".txt");
    for(int i = 0; i<filename.length(); ++i){
        if (filename[i] == '/' || filename[i] == ':')
            filename[i] = '-';
    }
    log.open(filename.c_str());
    if (log.fail())
        perror(filename.c_str());

    log<<"\n\nHuman won the tournament.\n";
    log.close();
    system("Pause");
}
Foi útil?

Solução

The date and time strings may have characters in them (like colons) that may not be legal characters for your file system.

Outras dicas

Use the following:

   log.open(filename.c_str());

The open method requires a char *, a.k.a. a C-style string, not a C++ std::string.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top