How do you detect if the USB cable is connected?

I just found that attempting to read input from Serial Monitor hangs up the sketch if the USB cable is not connected.

Is there a recommended way of dealing with this if it is not possible to detect the presence of a USB connection between PC and Arduino?

100k resistors from digital 1 and 0 to GND so they are not floating without the USB cable connected?

Or is there a way to avoid reading from Serial when the USB cable is not connected.

you are misreading the behavior. Serial.read() will try to read whatever is available or return -1 if there is nothing to read, regardless of the Serial console being opened or not.

you might have a

while(!Serial);

in your setup that gets your code to be stuck if the serial link cannot be established.

(deleted)

spycatcher2k:
check if the buffer has anything THEN read.

As a side comment, I now find this is not the best way. I understand for beginners it gives a safe thought process but it's not very efficient

Serial.available() returns the number of bytes available and does so through some maths in the circular buffer. Serial.read()returns -1 if there is nothing available tor read.

So if your code does not depend on having n bytes already in the incoming buffer (and it should not, you should read as they come in) then I'm now preferring to write

int r;
...
  if ((r = Serial.read()) != -1) {
    // we received a byte, it's in the LSB of r
  }

which is faster. and in plain english you can understand what it does -->"if I have received a valid byte, then handle it"