How to stop the robot by ctrl+c in cpp?

Hi, a node can be shutdown with Ctrl+c in c++ because of the SIGINT handler, and that happens when ros::ok() returns false. In your code, it means that the while loop will drop out as soon as you hit Ctrl+c, so your thinking is correct here.

Have you tried removing the if (!ros::ok()){} and just send the stop command as soon as the loop exits?