Here's how it came about:
* Shooting galleries were popular attractions at these events.
* Prizes were awarded for successful shots.
* A cigar was often the prize for a close shot, but not a perfect one.
The idea was that you got "close" to winning the main prize (which might be something more valuable than a cigar) but only managed to snag a consolation prize.
Therefore, "close but no cigar" became a way to describe something that almost achieved success, but ultimately fell short.
The saying gained widespread popularity in the early 20th century and remains a common idiom today.