使用istream_iterator时获取\ n

时间:2014-02-19 14:29:05

标签: c++ iterator

我想使用istream_iterator(std::cin)

它为我提供了每个单词,但我正在寻找一种方法来定义\n有一个单词。 我的想法是我应该使用getline()上的迭代器和if iterator == end我返回\n并使用另一行。

这是一个好主意还是已经有一个内置的迭代器来完成这个。

编辑:(抱歉没被理解)

我的迭代器是这样创建的:

_file = ifsteam("path/to/file");
_tokens = TokenIterator(_file); // TokenIterator is an istream_iterator<string>

我正在使用getToken()

TokenIterator it = myClass.getToken();
TokenIterator end = myClass.getEnd();

while (it != end)
{
  std::cout << *it << endl;
  it = myClass.getToken();
}

和getToken看起来像这样

const TokenIterator & getToken()
{
  return *tokens++;
}

如果我的文件有

1 2 3 \ n4

我的getToken返回:

  • 1
  • 2
  • 3
  • 4

但我希望它能够回归:

  • 1
  • 2
  • 3
  • ( “\ n” 个)
  • 4

1 个答案:

答案 0 :(得分:0)

试试这个:\\n

在字符串中将“\ n”替换为“\\ n”。别忘了\r\n

示例:

#include <iostream>

// searchAndReplace by Loki Astari http://stackoverflow.com/questions/1452501/string-replace-in-c
// thanks to him

void searchAndReplace(std::string& value, std::string const& search,std::string const& replace)
{
  std::string::size_type  next;

  for(next = value.find(search);        // Try and find the first match
      next != std::string::npos;        // next is npos if nothing was found
      next = value.find(search,next)    // search for the next match starting after
    // the last match that was found.
      )
       {
          // Inside the loop. So we found a match.
          value.replace(next,search.length(),replace);   // Do the replacement.
          next += replace.length();                      // Move to just after the replace
              // This is the point were we start
          // the next search from.
        }
}

int main()
{
  std::string s = "123\n4\n5";
  std::cout << s << std::endl;
  searchAndReplace(s, "\n", "\\n"); // just do this. you can check for /r/n too.
  std::cout << s << std::endl;
}

输出:

123
4
5
123\n4\n5