【问题标题】:c++ removing whitespace fails by using iteratorsc ++使用迭代器删除空格失败
【发布时间】:2016-09-08 13:51:51
【问题描述】:

此代码按预期编译和工作,但由于某种原因,注释行没有任何人可以告诉我原因。

#include <iostream>

int main()
{
    std::cout << "Enter a line:\n";
    std::string Line;
    std::getline(std::cin,Line);
    const std::string Whitespace = " \t\t\f\v\n\r";
    //std::string Line= std::string(Line.find_first_not_of(Whitespace),Line.find_last_not_of(Whitespace)+1); // Why doesnt this work?
    std::string Line= Line.substr(Line.find_first_not_of(Whitespace),Line.find_last_not_of(Whitespace)+1);
    std::cout << "You entered:" << Line << "\n";
}

编辑我的印象是 find las 返回一个迭代器而不是 size_t 所以这就是我感到困惑的原因

【问题讨论】:

  • find_first_not_of() 返回什么?看起来像索引而不是迭代器。
  • “由于某种原因不起作用”。它怎么不起作用?您是在要求人们猜测您的输入和输出。
  • 没有任何作用!注意string substr (size_t pos = 0, size_t len = npos) const;中的长度
  • 好的,所以我们知道您不会出错。您能否分享一些不按您认为的方式工作的输入/输出?

标签: c++ string iterator


【解决方案1】:

不仅是注释行,如果字符串开头有空格,另一行也会失败。

第一行失败(编译)因为string::find_first_not_of 返回size_t。而从两个尺寸构造string 是没有意义的。

第二行可能会失败,因为string::substr 接受长度(不是结束)作为它的第二个参数。

【讨论】:

  • 哦,你没有包含 (或者你在编译器设置中包含它?)
猜你喜欢
  • 2010-10-19
  • 2016-07-29
  • 1970-01-01
  • 2011-12-21
  • 2019-11-14
  • 2020-07-31
  • 1970-01-01
  • 2016-11-29
  • 2012-01-13
相关资源
最近更新 更多