In Afghanistan, the issue was that the country does not really make sense. The central government is usually weak and illegitimate, and it doesn't have effective control over most of the country. The US went in with a small force and quickly defeated the central government. But because they lacked the manpower to control the country, they created a new central government, which was again too weak and illegitimate for the task. And then the situation just dragged on, until the US lost interest.
As for the Vietnam War, cities rarely changed hands in the war before the US started withdrawing its troops. The US was unwilling to invade North Vietnam, because it was afraid of an outcome similar to the Korean War, where it would have to face China and/or the USSR directly. And North Vietnam was too weak to invade the South.