子字符串给出看似随机的结果,即使其参数看起来正确

Substring gives seemingly random results, even when its parameters seem correct

本文关键字:参数 看起来 结果 字符串 随机      更新时间:2023-10-16

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

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子字符串时,它返回的文本长度从三到一个字符不等。对我的错误有任何见解吗?

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

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

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

希望这有帮助!