When installing a toilet, the most important measurement to make is the toilet drain pipe's rough-in. This measurement will let you know which size toilet you need to buy and which sizes to avoid.
While a bathroom can technically have any number of rough-in sizes, only a few are commonly used.
The Standard Rough-In
A toilet rough-in is the distance from the center of the drain pipe in your bathroom floor to the wall sitting behind the toilet. Since the toilet tank sits behind the bowl, the rough-in makes sure that the toilet and tank can fit once the toilet is attached above the drain pipe.
In the United States, many toilets have a rough-in of 12 inches.
Measuring a Rough-In
Since the rough-in measurement is taken from the exact center of the drain pipe, you will have to use something else to measure from if a toilet is already installed. The two bolts that hold your toilet to the floor are located on both sides of the drain, exactly in the center.
Measure from the middle of the toilet bolts to the wall behind the toilet. If you have molding at the bottom of the wall, ignore it and measure to the actual wall, since the toilet tank will sit well above the molding.
While 12 inches is standard for a toilet today, many older homes have toilets that were installed with different rough-ins. Also, if a floor joist happens to be exactly 12 inches from the wall, the builder may have used a different rough-in to avoid having the toilet drain damage the integrity of the floor.
In almost all cases, if a rough-in isn't 12 inches, it is either 10 inches or 14 inches. Many home improvement stores will have a few alternate rough-in toilets in stock, or at least have a way to order them.
Poor Rough-In Solutions
If a rough-in doesn't match a toilet, the best option is to just take the toilet back and get a new one. If the toilet rough-in is shorter than the pipe rough-in, you can simply the toilet anyway and place a 2-inch piece of wood behind the tank to brace it against the wall.
Otherwise, you can completely redo the plumbing or install an offset toilet flange. This flange gets placed between the drain pipe and the toilet, and offsets the opening by as much as 2 inches.