-3

Let's say I have a string "file1\nfile2\nfile3".

I want to print out:

file1
file2
file3

How can I do this without using a string stream?

Note: When I say string, I mean the string object in C++.

I'm sorry if this is a stupid question; I'm completely new to C++;

Human Cyborg Relations
  • 1,202
  • 5
  • 27
  • 52
  • 7
    Why don't you just print out the string as is, without splitting it at all? – aschepler Sep 09 '17 at 22:34
  • Possible duplicate https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string – Galik Sep 09 '17 at 22:39
  • `string s = "file1\nfile2\nfile3"; cout << s << '\n';` – melpomene Sep 09 '17 at 22:51
  • If you are "completely new to C++", then the way you need to learn C++ is [by reading a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), or attending a class. You are not going to learn C++ by asking basic questions, one at a time, on some web site and hoping that you'll get an answer in the next day, or two. – Sam Varshavchik Sep 09 '17 at 23:14
  • Crap. So much for my proposed programming text: Learn C++ in 365 years. – user4581301 Sep 09 '17 at 23:32

1 Answers1

0

The following should work and lets you specify a multichar delim:

void split_and_print(const std::string & data, const std::string & delim =std::string{"\n"}){
    if (!delim.length()){
        std::cout<<data<<std::endl;
        return;
    }
    auto last  = data.begin();
    auto found = last;
    while (found != data.end()){
        found = std::search(last, data.end(), delim.begin(), delim.end());
        std::cout<<std::string(last, found)std::endl;
        last = found + delim.length();   
    }
}
Hatatister
  • 962
  • 6
  • 11