idioms io - RawIron/learn-cpp GitHub Wiki

cin, cout

  • read from stdin
  • capture and restore iosflags

https://stackoverflow.com/questions/2273330/restore-the-state-of-stdcout-after-manipulating-it

  • read n values
// the first time it reads len values from cin
// the second call reads 0 values ..
// somehow the first call empties the content of cin
vector<int> read_n() {
    vector<int> scores{};
    const int len = 5;
    copy_if(
        istream_iterator<int>(cin),
        istream_iterator<int>(),
        back_inserter(scores),
        [count=len] (int) mutable { return count && count--; }
    );
}

https://stackoverflow.com/questions/54254075/how-to-read-n-integers-into-a-vector

  • read csv
#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings

iterate over words

#include <string>
#include <sstream>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "And I feel fine...";

    istringstream iss(sentence);
    vector<string> tokens{istream_iterator<string>{iss},
                          istream_iterator<string>{}};
}

https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string

⚠️ **GitHub.com Fallback** ⚠️