简体   繁体   中英

Get the \n when using istream_iterator

I would like to use an istream_iterator(std::cin)

It gives me each word however I am looking for a way to define the \\n has a word. My idea was that I should use an iterator on getline() and if iterator == end I return \\n and take the other line.

Is this a good idea or is there already a built-in iterator to accomplish this.

EDIT: (sorry for not being understood)

My iterator is created like this:

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

I am using a getToken()

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

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

and getToken looks like this

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

If my file has

1 2 3\\n4

My getToken returns:

  • 1
  • 2
  • 3
  • 4

But I want it to return :

  • 1
  • 2
  • 3
  • ("\\n")
  • 4

Try this : \\\\n

Replace "\\n" with "\\\\n" in your string. Dont forget \\r\\n too.

sample :

#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;
}

Output :

123
4
5
123\n4\n5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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