Pregunta

I am a newbie programmer and am interested in competitive programming. I made a grader for COCI problems recently. In a function of this code, I take input from input files using a loop. Its file opening part looks like this -

int next(int id)
{

    // [[OPEN FILES]] -----------------------

    string name1 = probid+".in." + itoa(id);
    string name2 = probid + "OUTPUT" +".out." + itoa(id);

    FILE *fp1 = fopen(name1.c_str(), "r");   
    if(!fp1) return 0;                            // no file left?
    FILE *fp2 = fopen(name2.c_str(), "w");        

    // process data
}

"id" changes and opens the input files and writes results to output file. The main problem is I have to read data using (fscanf) but I want to take input using cin, cout. (things freopen offers)

but when I run the loop using freopen, it fails to read input from more than one file . so I have to use fopen().

Is there anyway I can use cin, cout to take input from files using this function?

¿Fue útil?

Solución

std::cin and std::cout are stream objects that refer to standard input and standard output. However, in C++ we also have stream classes for files: std::ifstreamand std::ofstream. They use exactly the same >> and << functions.

These file stream classes have a member .open() which can open a new file, provided that you have closed the previous file.

Otros consejos

you can use freopen ().

freopen ("direcotry/to/input/file", "r", stdin); // second argument is opening mode

freopen ("direcotry/to/output/file", "w", stdout);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top