new to c++ . i am trying to count back in a sentence to find the last white space then reveal the characters after it. i am kinda stuck in the while loop and i was wondering if anyone could explain where i am going wrong . what i want is to find the last white space give it a position and print the characters from the space found to the last character . not looking to be spoon fed just to see if i am thinking about this correctly. i have taken a array , counted the size of it , then converted it to characters , i tried to count back from the last character to the last white space of the sentence and used substr to print the findings, kinda lost though any advice would be nice . thanks john.
int main()
{
string strSentence;
int strLength,x;
char chrX[50];
cout << "\nInput a sentence please: ";
getline(cin , strSentence);
cout << "\n";
strLength = strSentence.length();
cout << "string length is " << strLength;
x = strLength;
strcpy(chrX,strSentence.c_str());
do
{
strLength--;
}
while (chrX != ' ');
cout << " this was the last word" << strSentence.substr(x,strLength);
btw i declared x to the length thinking it will hold the original length and the strLength-- will be the white space location , if you get me. i think i might be wrong though :-)
If your trying to isolate the last word. Then I'd not bother going to a character array. It's just creating more hassle.
Unfortunately, Telling you how to do it is really giving you the answer. So I'll try to give you as much help as possible without the answer :) The code is only 2 lines.
1 2
int lastSpace = strSentence.find_last_of(' ');
string lastWord = strSentence.substr(// etc);
Create a pointer to the string.
Point the pointer to the end of the string.
--pointer until you find the first white space.
Print results from pointer until null terminating character.
@Sammie: That's over-complicating the solution. You can write what he is asking for in 2 lines of code nicely formatted. No need to start getting pointers involved and doing it manually.
can anyone see why it just prints the original entered string, my understanding is lastWord should have been printed, meaning the location of last white space +1 with a length of X amounts of digits got from the total string length - the location of the last space . it just gives me the whole string back , lol . i honestly thought i had this :-)
Just be aware, that find_last_of (etc) will return -1 if there is no match. So you wanna check for that before you try and use substr, otherwise you may end up crashing the application with a buffer-overrun.