I am participating in some programming competitions, and on many problems there’s the need to read strings from an input file. Obviously performance is a big issue on those competitions, and strings might be huge, so I am trying to understand the most efficient way to read those strings.
My guess is that reading the strings char by char, with getchar(), is the fastest you can go. That’s because even if you use other functions, say fgets() or getline(), those functions will still need to read every char anyway.
Update: I know that I/O won’t be a bottleneck on most algorithmic problems. That being said I would still very much like to know what’s the fastest way you can use to read strings, should this become an issue on any future problem.
You can use
std::istream::read()function to read a chunk of unformatted data. It is relatively faster precisely because the data is unformatted. All overloads ofoperator>>read formatted data which makes reading from stream slower compared toread().Similarly, you can use
std::ostream::write()function to write a chunk of data to output stream at once.