子字符串给出看似随机的结果,即使其参数看起来正确
Substring gives seemingly random results, even when its parameters seem correct
我的代码应该以两个或多个作者姓名读取,用逗号分隔,然后返回第一个作者的姓氏。
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));
希望这有帮助!
相关文章:
- std::vector的包装器,使数组的结构看起来像结构的数组
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 尽管一切看起来都很好,但值不会交换
- 自制的上衣:看起来一样,但不完全相同
- 如何使它看起来像正在下的雪
- 如何用逗号分隔输出?如何改进此代码以使其看起来更体面?
- 我的代码看起来不错,但某些输入会导致不需要的输出
- 为什么这个结构的大小是 40,而它看起来应该是 12/24?
- 我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)
- 结构化绑定:当某些内容看起来像引用并且行为类似于引用,但它不是引用时
- 如何使QTextEdit看起来被禁用
- 在正确性或良好的代码结构方面,这种动态对象创建看起来如何
- 'xxxx' :看起来像一个函数定义,但没有参数列表;跳过表观身体
- SSSE3 的 strncpy 段错误 尽管所有参数看起来都正确
- 钩子内部函数:参数看起来是什么样的?
- 当构造将std::less作为参数时,对象类型看起来很奇怪
- 子字符串给出看似随机的结果,即使其参数看起来正确
- 引用看起来是恒定的.为什么不在参数中呢?
- table':看起来像一个函数定义,但没有参数列表.——同时试图创造财产