Hello, 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 -
"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, it fails to read input from more than one file using freopen. so I have to use fopen().
Is there anyway I can use cin, cout to take input from files using this function?
The local variables FILE* fp1 and FILE* fp2 have automatic storage duration.; the life time of the objects are over when the function returns.
std::freopen() reassigns an existing file stream stream to a different file.
When next() is called, fp1 and fp2 from the previous invocation of the function no longer exist.
I edited my code, with stdin as third parameter, function read 1 input file, but now it doesn't even read 1 file. I double checked file name and directories. It doesn't read the input file. (returns "nope").
Tried it without fclose() at the bottom. still same result.. :(
int next(int id)
{
string name1 = probid+".in." + itoa(id);
string name2 = probid + "OUTPUT2" +".out." + itoa(id);
static FILE *fp1 = 0 ;
if(fp1) fp1 = freopen( name1.c_str(), "r", fp1 ); // if it is already open, reopen it
else fp1 = fopen( name1.c_str(), "r" ) ; // else open it
if (!fp1) { cout << "nope\n"; return 0; }
// likewise for fp2
// ...
// do not close the files; we intend to use freopen them later
// fclose(fp1);
// fclose(fp2);
// or if we do close them, reset fp1 and fp2 to null pointers.
}
now it's just taking input from me manually (when using cin, cout) and giving output manually (on the screen, not in file)
I'm afraid I don't follow - isn't that what std::cin and std::cout are supposed to do?
Also, is there a specific reason you're using the C file-handling functions as opposed to C++'s <fstream>?