0

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?

Labib666
  • 3
  • 1
  • 3

2 Answers2

1

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

you can use freopen ().

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

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

Moha the almighty camel
  • 4,327
  • 4
  • 30
  • 53
  • I cant read using freopen. using freopen I can only read 1 file. cant read the rest of them. :-/ This is the progress of this thread in cplusplus.com forum - http://www.cplusplus.com/forum/general/112428/ – Labib666 Oct 03 '13 at 10:15
  • I joined couple of programming contests, and never had to read from more the one file. usually, freopen is part of the C++ source code template for these contests. – Moha the almighty camel Oct 03 '13 at 10:18
  • you are using two files, one for input and one for output. so use freopen twice, each time redirecting a different stream. – Moha the almighty camel Oct 03 '13 at 10:23
  • COCI problems for past years cannot be graded online. But they provide test data for the problems. Since there are many test data, (5-10 per problem) taking I/O every file is pretty time consuming. so this program reads data from all testcases, creates a output, and matches it the official output, saving me the pain of running all the cases manually. full code http://ideone.com/TMbx3s – Labib666 Oct 03 '13 at 10:27