繁体   English   中英

使用istream_iterator时获取\\ n

[英]Get the \n when using istream_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

试试这个: \\\\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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM