A tricky decision and a constant debate between people who have been to both!
I've just come back from holiday having been to both. Barcelona was busy, fun and lively. It had the tourist spots, the beach and lots of tapas places on offer- Las Ramblas being a fab spot for food and drinks. As much as Barcelona is often a fave due to its city life with the beach so close, Madrid also had a lot going for it. I stayed in a hostel (the hat) which was incredible and a 1 minute walk from the main Plaza. A lovely, more calm, area with so many shops and restaurants around. El Retiro Park was beautiful and the rooftop bars were lovely (the hat had it's own really affordable one). The biggest difference I would say is Madrid has all the places within walking distance, in Barcelona you often find yourself walking half an hour before getting anywhere. Madrid is perfect for a short stay and fitting everything in, but Barcelona may be more suited if you plan to stay 4/5 days.
I'd bear in mind that in both places (in particular Barcelona) pick pocketing is a big problem. Barcelona also had protests on during my stay, so I'd advise keeping in the loop with the news and seeing what's going on before heading out. Hope this helps!