Okay so I am working on an external polyphase sort/merge and I am using peek to look at the next value in a file, there is just one problem. My peek gives me the wrong number, but if i just read the value it gives me the right value. What could be wrong?

Dani AI

Generated

Short diagnosis and a practical pattern for external merging: the stream peek() returns the next raw character (an int_type holding the character code or EOF), not the next parsed integer token. If the file contains the characters 123, peek() yields the character '1' (ASCII 49), so treating that value as the full numeric key produces an incorrect result. That is the root cause of the behavior noted by and anticipated by .

A more robust and idiomatic approach for a polyphase sort/merge is a one-element lookahead per input run: read the next integer from each file once and keep it in memory for comparisons. This removes any need to “peek” at the stream while merging and keeps I/O simple and fast. Example of the lookahead holder:

struct Run {
  std::ifstream in;
  bool hasNext;
  long long next;

  Run(const std::string &path) : in(path), hasNext(false), next(0) { advance(); }

  void advance() {
    if (in >> next) hasNext = true;
    else hasNext = false;
  }
};

Using Run instances, the merge loop repeatedly selects the run with the smallest next, writes that value out, then calls advance() on that run to refill. This pattern is safe for large files and avoids fragile stream tricks.

The tellg()/seekg() trick shown by can work for regular, seekable files: save position, perform a formatted read, then seekg back. Important caveats: some streams are non‑seekable (pipes/stdin), tellg() can be invalid, formatted extraction can set stream error flags that must be handled, and putback/unget are limited to a few chars and are unreliable for multi‑digit tokens. For very large datasets, consider binary fixed‑width records (with attention to endianness) to avoid parsing overhead altogether.

Recommended Answers

All 3 Replies

peek() reads a single character from the text file -- it can't be used to read integers except that it read a single digit.

is there anyway i can peek() and get a 2 or more digit number?

You cannot peek for more than one character. However, you can use the tellg and seekg functions to restore the original position after having done a multi-character reading. As so:

int peek_int(std::istream& in) {
  std::streampos orig_pos = in.tellg();
  int result = 0;
  in >> result;
  in.seekg(orig_pos);
  return result;
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.