Tragically, there are very few public toilets in Rome (hence the horrible odor you’ll encounter near alleyways and on the beautiful but isolated banks of the Tiber at Lungotevere). And many of the ones that are available are very nasty indeed.
A few Metro and train stations have them, usually requiring a €1 coin to enter. Some of these are even clean-ish, particularly in Termini.
What do Rome locals do when they need the bathroom?
By law, as part of their licensing conditions, every bar (the word for café here) must allow their customers to use the bathroom – though not anyone who just walks in off the street. To become a customer, even if you’re not in the mood for another coffee, buying a small bottle of water or a pack of gum will suffice.
In practice this can prove fraught, as in highly trafficked areas you may sometimes find that “the bathroom is out of order”.
If this should happen, some locals have told me you should mention the cops (“vigili“), since it is illegal to have premises with tables for eating or drinking without viable bathroom facilities.
My advice is, find another bar. If it’s a crowded, busy bar then you can probably just walk in, scope out where the bathroom is, and brazen it out – my thinking being, what’s the worst they can do if you’ve already made it into the stall – shout at you as you leave?
However if it’s a small/quiet place, then it’s polite to ask to use the bathroom: “posso usare il bagno?” (POSS-oh oo-ZAR-eh eel BAN-yo?) or just ask where the bathroom is: “dov’è il bagno?” (doh-VEH eel BAN-yo?), but to be really polite then you should indeed buy a coffee, a bottle of water, or a pack of gum, then ask to use the bathroom and they’ll be perfectly happy to allow you.
If you’re really worried, though, there’s an app for Android and iOS that gives you a map of the city with the nearest bathrooms shown and details about them (Italian language only though). Be warned though: they are very unlikely to be sanitary.