How to find a char in a string backwards

Hi, how if i have the following string: "My name is Bobby" how can I find the # of where the space is before Bobby (it should be 10)

I tried str_name.rfind(" ");
but i get -1. So how do I do it?
I did not find out any error


1
2
3
4
5
std::string s( "My name is Bobby" );

std::string::size_type pos = s.rfind( " " );

std::cout << pos << std::endl;


The output is 10.

EDIT: I think I have understood what is the reason that you got -1. It seems that you are using operator >> to enter str_name. It enters only one word. You should use std::getline( std::cin, str_name ) instead of operator >>.
Last edited on
Topic archived. No new replies allowed.