2

我的代码应该读取两个或多个作者姓名,用逗号分隔,然后返回第一作者的姓氏。

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 ;

但是,当我尝试检索AuthorLast子字符串时,它返回的文本从三到一个字符过长。对我的错误有任何见解吗?

4

1 回答 1

3

C++substr方法不采用开始和结束位置。相反,它需要一个起始位置和许多要读取的字符。结果,您传入的参数告诉substr从位置开始AuthorBlankLocation + 1,然后AuthorCommaLocation - 1从该点向前读取字符,这可能是太多字符了。

如果要指定开始和结束位置,可以使用string构造函数的迭代器版本:

string AuthorLast(authors.begin() + (AuthorBlankLocation + 1),
                  authors.begin() + (AuthorCommaLocation - 1));

希望这可以帮助!

于 2013-01-31T02:54:55.880 回答