How exactly is the squeeze theorem used in this example?

$$\lim_{x \to \infty} \dfrac{\cos x}{x}$$

Apparently this is $0$ by the squeeze theorem, because $-\dfrac{1}{x} \leq \dfrac{\cos x}{x} \leq \dfrac{1}{x}$ for all $x>0$

I understand the squeeze theorem intuitively, but I don't understand where these 2 functions come from. How do you know that the above inequality holds? Are you supposed to figure that out by yourself?

Similarly, for $\lim_{x \to 0} x\sin(\dfrac{1}{x})$ is $0$ by the squeeze theorem because $-|x| \leq x\sin(\dfrac{1}{x}) \leq |x|$ for all $x \neq 0$. Where do these functions come from? Is there any systematic way to choose them?

We have $$-1 \leq \cos(x) \leq 1, \quad \text{ and } \quad -1 \leq \sin\left(\frac{1}{x}\right) \leq 1$$ for every $x \in \mathbb{R},x \neq 0$. Now divide the first equation by $x>0$ and multiply the second by $|x|$. It is maybe not 100% systematic but it is very common to use such bounds on $\sin, \cos$ and then use the squeezing theorem (and it's worth it to try).
One thing you must always bear in mind that the $\cos$ and $\sin$ functions are both bounded from above and below ($-1\leq \cos x, \sin x \leq 1$). It is one of the first things you try when calculating limits.
All you need is that the trigonometric functions only take values between $-1$ and $+1$. That explains both inequalities.
You generally need to find an upper bound and a lower bound for the given function whose limit you want to evaluate. In most of the cases you can write the function as a product of two functions $f$ and $g$ such that at least for one of them it is very easy to find these bounds (in this case $\cos x$), if the bounds are $M$ and $m$ respectively then use $mg(x)$ and $Mg(x)$ as the squeezing functions.