My code should read in two or more authors names, separated by a comma, then return the last name of the first author.
cout << "INPUT AUTHOR: " << endl ;
getline(cin, authors, '\n') ;
int AuthorCommaLocation = authors.find(",",0) ;
int AuthorBlankLocation = authors.rfind(" ", AuthorCommaLocation) ;
string AuthorLast = authors.substr(AuthorBlankLocation+1, AuthorCommaLocation-1) ;
cout << AuthorLast << endl ;
However, when I try and retrieve the AuthorLast substring, it returns text anywhere from three to one character too long. Any insight into my error?
The C++
substrmethod does not take in a start and end position. Instead, it takes in a start position and a number of characters to read. As a result, the arguments you are passing in are tellingsubstrto start at positionAuthorBlankLocation + 1and then to readAuthorCommaLocation - 1characters from that point forward, which is probably far too many characters.If you want to specify the begin and end positions, you can use the iterator version of the
stringconstructor:Hope this helps!