我的代码应该读取两个或多个作者姓名,并用逗号分隔,然后返回第一个作者的姓氏。
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));
希望这有帮助!
关于c++ - 即使其参数看起来正确,子字符串也会给出看似随机的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14617700/