Tinker9 70bd052 (Thu Nov 9 12:11:35 2023 -0800)
Loading...
Searching...
No Matches
ioread.h
1#pragma once
2#include "tool/iotext.h"
3#include "tool/tinkersuppl.h"
4#include <iostream>
5
6namespace tinker {
13template <class Arg>
14int ioReadString(Arg& arg, const char* str, size_t len)
15{
16 const int succeed = 0;
17 const int fail = 1;
18 std::istringstream iss(std::string(str, len));
19 Arg tmp;
20 iss >> tmp;
21 if (iss.fail()) {
22 return fail;
23 } else {
24 arg = tmp;
25 return succeed;
26 }
27}
28
29inline int ioReadString(std::string& arg, const char* str, size_t len)
30{
31 const int succeed = 0;
32 arg = std::string(str, len);
33 return succeed;
34}
35
36template <class Arg, size_t Len>
37int ioReadString(Arg& arg, const char (&src)[Len])
38{
39 return ioReadString(arg, src, Len);
40}
42
54template <class Arg, class Invalid>
55void ioReadStream(Arg& arg, std::string prompt, Arg auto_fill,
56 Invalid&& invalid, std::istream& istream = std::cin)
57{
58 bool is_cin = (&istream == &std::cin);
59 int input_fail = invalid(arg); // True if arg is out of range.
60 std::string line;
61 while (input_fail) {
62 std::printf("%s", prompt.c_str());
63 std::fflush(stdout);
64 if (is_cin) {
65 line = tinker_f_read_stdin_line();
66 } else {
67 istream.clear(); // Reset failbit.
68 // Expunge the remaining input and invisible '\n',
69 // only if using operator<<;
70 // unnecessary if std::getline(...) is used instead.
71 // istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
72 std::getline(istream, line);
73 }
74 auto vs = Text::split(line);
75 if (vs.size() == 0) {
76 arg = auto_fill;
77 input_fail = false;
78 } else {
79 // True if failed to parse input.
80 input_fail = ioReadString(arg, line.data(), line.size());
81 }
82 if (!input_fail) input_fail = invalid(arg);
83 }
84}
85
88template <class T>
89void ioRewindStream(T& stream)
90{
91 stream.clear();
92 stream.seekg(0);
93}
94}
int ioReadString(Arg &arg, const char *str, size_t len)
Reads ONE value from a string and save to arg. arg will not change until the reading successfully exi...
Definition: ioread.h:14
void ioReadStream(Arg &arg, std::string prompt, Arg auto_fill, Invalid &&invalid, std::istream &istream=std::cin)
Tests the validity of arg. If invalid, read ONE value from an std::istream object....
Definition: ioread.h:55
void ioRewindStream(T &stream)
Rewind a stream object.
Definition: ioread.h:89
static std::vector< std::string > split(std::string str, std::string delimiters=whitespaces)
Splits a string str by delimiters and returns a vector of strings.
Definition: testrt.h:9